
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml" lang="zh_CN">
  <head>
    <meta charset="utf-8" />
    <title>argparse --- 命令行选项、参数和子命令解析器 &#8212; Python 3.7.8 文档</title>
    <link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/language_data.js"></script>
    <script type="text/javascript" src="../_static/translations.js"></script>
    
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    
    <link rel="search" type="application/opensearchdescription+xml"
          title="在 Python 3.7.8 文档 中搜索"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="关于这些文档" href="../about.html" />
    <link rel="index" title="索引" href="../genindex.html" />
    <link rel="search" title="搜索" href="../search.html" />
    <link rel="copyright" title="版权所有" href="../copyright.html" />
    <link rel="next" title="getopt --- C 风格的命令行选项解析器" href="getopt.html" />
    <link rel="prev" title="time --- 时间的访问和转换" href="time.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/3/library/argparse.html" />
    
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
    
    
    
    <style>
      @media only screen {
        table.full-width-table {
            width: 100%;
        }
      }
    </style>
 

  </head><body>
  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>导航</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="总目录"
             accesskey="I">索引</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python 模块索引"
             >模块</a> |</li>
        <li class="right" >
          <a href="getopt.html" title="getopt --- C 风格的命令行选项解析器"
             accesskey="N">下一页</a> |</li>
        <li class="right" >
          <a href="time.html" title="time --- 时间的访问和转换"
             accesskey="P">上一页</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">3.7.8 Documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python 标准库</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="allos.html" accesskey="U">通用操作系统服务</a> &#187;</li>
    <li class="right">
        

    <div class="inline-search" style="display: none" role="search">
        <form class="inline-search" action="../search.html" method="get">
          <input placeholder="快速搜索" type="text" name="q" />
          <input type="submit" value="转向" />
          <input type="hidden" name="check_keywords" value="yes" />
          <input type="hidden" name="area" value="default" />
        </form>
    </div>
    <script type="text/javascript">$('.inline-search').show(0);</script>
         |
    </li>

      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-argparse">
<span id="argparse-parser-for-command-line-options-arguments-and-sub-commands"></span><h1><a class="reference internal" href="#module-argparse" title="argparse: Command-line option and argument parsing library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">argparse</span></code></a> --- 命令行选项、参数和子命令解析器<a class="headerlink" href="#module-argparse" title="永久链接至标题">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified added">3.2 新版功能.</span></p>
</div>
<p><strong>源代码：</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.7/Lib/argparse.py">Lib/argparse.py</a></p>
<hr class="docutils" />
<div class="sidebar">
<p class="sidebar-title">教程</p>
<p>此页面包含该 API 的参考信息。有关 Python 命令行解析更细致的介绍，请参阅 <a class="reference internal" href="../howto/argparse.html#id1"><span class="std std-ref">argparse 教程</span></a>。</p>
</div>
<p><a class="reference internal" href="#module-argparse" title="argparse: Command-line option and argument parsing library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">argparse</span></code></a> 模块可以让人轻松编写用户友好的命令行接口。程序定义它需要的参数，然后 <a class="reference internal" href="#module-argparse" title="argparse: Command-line option and argument parsing library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">argparse</span></code></a> 将弄清如何从 <a class="reference internal" href="sys.html#sys.argv" title="sys.argv"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.argv</span></code></a> 解析出那些参数。 <a class="reference internal" href="#module-argparse" title="argparse: Command-line option and argument parsing library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">argparse</span></code></a> 模块还会自动生成帮助和使用手册，并在用户给程序传入无效参数时报出错误信息。</p>
<div class="section" id="example">
<h2>示例<a class="headerlink" href="#example" title="永久链接至标题">¶</a></h2>
<p>以下代码是一个 Python 程序，它获取一个整数列表并计算总和或者最大值：</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">argparse</span>

<span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">description</span><span class="o">=</span><span class="s1">&#39;Process some integers.&#39;</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;integers&#39;</span><span class="p">,</span> <span class="n">metavar</span><span class="o">=</span><span class="s1">&#39;N&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="s1">&#39;+&#39;</span><span class="p">,</span>
                    <span class="n">help</span><span class="o">=</span><span class="s1">&#39;an integer for the accumulator&#39;</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--sum&#39;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s1">&#39;accumulate&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;store_const&#39;</span><span class="p">,</span>
                    <span class="n">const</span><span class="o">=</span><span class="nb">sum</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="nb">max</span><span class="p">,</span>
                    <span class="n">help</span><span class="o">=</span><span class="s1">&#39;sum the integers (default: find the max)&#39;</span><span class="p">)</span>

<span class="n">args</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">()</span>
<span class="nb">print</span><span class="p">(</span><span class="n">args</span><span class="o">.</span><span class="n">accumulate</span><span class="p">(</span><span class="n">args</span><span class="o">.</span><span class="n">integers</span><span class="p">))</span>
</pre></div>
</div>
<p>假设上面的 Python 代码保存在名为 <code class="docutils literal notranslate"><span class="pre">prog.py</span></code> 的文件中，它可以在命令行运行并提供有用的帮助信息：</p>
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$</span> python prog.py -h
<span class="go">usage: prog.py [-h] [--sum] N [N ...]</span>

<span class="go">Process some integers.</span>

<span class="go">positional arguments:</span>
<span class="go"> N           an integer for the accumulator</span>

<span class="go">optional arguments:</span>
<span class="go"> -h, --help  show this help message and exit</span>
<span class="go"> --sum       sum the integers (default: find the max)</span>
</pre></div>
</div>
<p>当使用适当的参数运行时，它会输出命令行传入整数的总和或者最大值：</p>
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$</span> python prog.py <span class="m">1</span> <span class="m">2</span> <span class="m">3</span> <span class="m">4</span>
<span class="go">4</span>

<span class="gp">$</span> python prog.py <span class="m">1</span> <span class="m">2</span> <span class="m">3</span> <span class="m">4</span> --sum
<span class="go">10</span>
</pre></div>
</div>
<p>如果传入无效参数，则会报出错误：</p>
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$</span> python prog.py a b c
<span class="go">usage: prog.py [-h] [--sum] N [N ...]</span>
<span class="go">prog.py: error: argument N: invalid int value: &#39;a&#39;</span>
</pre></div>
</div>
<p>以下部分将引导你完成这个示例。</p>
<div class="section" id="creating-a-parser">
<h3>创建一个解析器<a class="headerlink" href="#creating-a-parser" title="永久链接至标题">¶</a></h3>
<p>使用 <a class="reference internal" href="#module-argparse" title="argparse: Command-line option and argument parsing library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">argparse</span></code></a> 的第一步是创建一个 <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> 对象：</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">description</span><span class="o">=</span><span class="s1">&#39;Process some integers.&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p><a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> 对象包含将命令行解析成 Python 数据类型所需的全部信息。</p>
</div>
<div class="section" id="adding-arguments">
<h3>添加参数<a class="headerlink" href="#adding-arguments" title="永久链接至标题">¶</a></h3>
<p>给一个 <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> 添加程序参数信息是通过调用 <a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_argument()</span></code></a> 方法完成的。通常，这些调用指定 <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> 如何获取命令行字符串并将其转换为对象。这些信息在 <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code></a> 调用时被存储和使用。例如：</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;integers&#39;</span><span class="p">,</span> <span class="n">metavar</span><span class="o">=</span><span class="s1">&#39;N&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="s1">&#39;+&#39;</span><span class="p">,</span>
<span class="gp">... </span>                    <span class="n">help</span><span class="o">=</span><span class="s1">&#39;an integer for the accumulator&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--sum&#39;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s1">&#39;accumulate&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;store_const&#39;</span><span class="p">,</span>
<span class="gp">... </span>                    <span class="n">const</span><span class="o">=</span><span class="nb">sum</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="nb">max</span><span class="p">,</span>
<span class="gp">... </span>                    <span class="n">help</span><span class="o">=</span><span class="s1">&#39;sum the integers (default: find the max)&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>然后，调用 <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code></a> 将返回一个具有 <code class="docutils literal notranslate"><span class="pre">integers</span></code> 和 <code class="docutils literal notranslate"><span class="pre">accumulate</span></code> 两个属性的对象。<code class="docutils literal notranslate"><span class="pre">integers</span></code> 属性将是一个包含一个或多个整数的列表，而 <code class="docutils literal notranslate"><span class="pre">accumulate</span></code> 属性当命令行中指定了 <code class="docutils literal notranslate"><span class="pre">--sum</span></code> 参数时将是 <a class="reference internal" href="functions.html#sum" title="sum"><code class="xref py py-func docutils literal notranslate"><span class="pre">sum()</span></code></a> 函数，否则则是 <a class="reference internal" href="functions.html#max" title="max"><code class="xref py py-func docutils literal notranslate"><span class="pre">max()</span></code></a> 函数。</p>
</div>
<div class="section" id="parsing-arguments">
<h3>解析参数<a class="headerlink" href="#parsing-arguments" title="永久链接至标题">¶</a></h3>
<p><a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> 通过 <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code></a> 方法解析参数。它将检查命令行，把每个参数转换为适当的类型然后调用相应的操作。在大多数情况下，这意味着一个简单的 <a class="reference internal" href="#argparse.Namespace" title="argparse.Namespace"><code class="xref py py-class docutils literal notranslate"><span class="pre">Namespace</span></code></a> 对象将从命令行解析出的属性构建：</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;--sum&#39;</span><span class="p">,</span> <span class="s1">&#39;7&#39;</span><span class="p">,</span> <span class="s1">&#39;-1&#39;</span><span class="p">,</span> <span class="s1">&#39;42&#39;</span><span class="p">])</span>
<span class="go">Namespace(accumulate=&lt;built-in function sum&gt;, integers=[7, -1, 42])</span>
</pre></div>
</div>
<p>在脚本中，通常 <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code></a> 会被不带参数调用，而 <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> 将自动从 <a class="reference internal" href="sys.html#sys.argv" title="sys.argv"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.argv</span></code></a> 中确定命令行参数。</p>
</div>
</div>
<div class="section" id="argumentparser-objects">
<h2>ArgumentParser 对象<a class="headerlink" href="#argumentparser-objects" title="永久链接至标题">¶</a></h2>
<dl class="class">
<dt id="argparse.ArgumentParser">
<em class="property">class </em><code class="sig-prename descclassname">argparse.</code><code class="sig-name descname">ArgumentParser</code><span class="sig-paren">(</span><em class="sig-param">prog=None</em>, <em class="sig-param">usage=None</em>, <em class="sig-param">description=None</em>, <em class="sig-param">epilog=None</em>, <em class="sig-param">parents=[]</em>, <em class="sig-param">formatter_class=argparse.HelpFormatter</em>, <em class="sig-param">prefix_chars='-'</em>, <em class="sig-param">fromfile_prefix_chars=None</em>, <em class="sig-param">argument_default=None</em>, <em class="sig-param">conflict_handler='error'</em>, <em class="sig-param">add_help=True</em>, <em class="sig-param">allow_abbrev=True</em><span class="sig-paren">)</span><a class="headerlink" href="#argparse.ArgumentParser" title="永久链接至目标">¶</a></dt>
<dd><p>创建一个新的 <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> 对象。所有的参数都应当作为关键字参数传入。每个参数在下面都有它更详细的描述，但简而言之，它们是：</p>
<ul class="simple">
<li><p><a class="reference internal" href="#prog">prog</a> - 程序的名称（默认值：<code class="docutils literal notranslate"><span class="pre">sys.argv[0]</span></code>）</p></li>
<li><p><a class="reference internal" href="#usage">usage</a> - 描述程序用途的字符串（默认值：从添加到解析器的参数生成）</p></li>
<li><p><a class="reference internal" href="#description">description</a> - 在参数帮助文档之前显示的文本（默认值：无）</p></li>
<li><p><a class="reference internal" href="#epilog">epilog</a> - 在参数帮助文档之后显示的文本（默认值：无）</p></li>
<li><p><a class="reference internal" href="#parents">parents</a> - 一个 <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> 对象的列表，它们的参数也应包含在内</p></li>
<li><p><a class="reference internal" href="#formatter-class">formatter_class</a> - 用于自定义帮助文档输出格式的类</p></li>
<li><p><a class="reference internal" href="#prefix-chars">prefix_chars</a> - 可选参数的前缀字符集合（默认值： '-'）</p></li>
<li><p><a class="reference internal" href="#fromfile-prefix-chars">fromfile_prefix_chars</a> - 当需要从文件中读取其他参数时，用于标识文件名的前缀字符集合（默认值： <code class="docutils literal notranslate"><span class="pre">None</span></code>）</p></li>
<li><p><a class="reference internal" href="#argument-default">argument_default</a> - 参数的全局默认值（默认值： <code class="docutils literal notranslate"><span class="pre">None</span></code>）</p></li>
<li><p><a class="reference internal" href="#conflict-handler">conflict_handler</a> - 解决冲突选项的策略（通常是不必要的）</p></li>
<li><p><a class="reference internal" href="#add-help">add_help</a> - 为解析器添加一个 <code class="docutils literal notranslate"><span class="pre">-h/--help</span></code> 选项（默认值： <code class="docutils literal notranslate"><span class="pre">True</span></code>）</p></li>
<li><p><a class="reference internal" href="#allow-abbrev">allow_abbrev</a> - 如果缩写是无歧义的，则允许缩写长选项 （默认值：<code class="docutils literal notranslate"><span class="pre">True</span></code>）</p></li>
</ul>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.5 版更改: </span>增加了 <em>allow_abbrev</em> 参数。</p>
</div>
</dd></dl>

<p>以下部分描述这些参数如何使用。</p>
<div class="section" id="prog">
<h3>prog<a class="headerlink" href="#prog" title="永久链接至标题">¶</a></h3>
<p>默认情况下，<a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> 对象使用 <code class="docutils literal notranslate"><span class="pre">sys.argv[0]</span></code> 来确定如何在帮助消息中显示程序名称。这一默认值几乎总是可取的，因为它将使帮助消息与从命令行调用此程序的方式相匹配。例如，对于有如下代码的名为 <code class="docutils literal notranslate"><span class="pre">myprogram.py</span></code> 的文件：</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">argparse</span>
<span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s1">&#39;foo help&#39;</span><span class="p">)</span>
<span class="n">args</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">()</span>
</pre></div>
</div>
<p>该程序的帮助信息将显示 <code class="docutils literal notranslate"><span class="pre">myprogram.py</span></code> 作为程序名称（无论程序从何处被调用）：</p>
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$</span> python myprogram.py --help
<span class="go">usage: myprogram.py [-h] [--foo FOO]</span>

<span class="go">optional arguments:</span>
<span class="go"> -h, --help  show this help message and exit</span>
<span class="go"> --foo FOO   foo help</span>
<span class="gp">$</span> <span class="nb">cd</span> ..
<span class="gp">$</span> python subdir/myprogram.py --help
<span class="go">usage: myprogram.py [-h] [--foo FOO]</span>

<span class="go">optional arguments:</span>
<span class="go"> -h, --help  show this help message and exit</span>
<span class="go"> --foo FOO   foo help</span>
</pre></div>
</div>
<p>要更改这样的默认行为，可以使用 <code class="docutils literal notranslate"><span class="pre">prog=</span></code> 参数为 <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> 指定另一个值：</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;myprogram&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">print_help</span><span class="p">()</span>
<span class="go">usage: myprogram [-h]</span>

<span class="go">optional arguments:</span>
<span class="go"> -h, --help  show this help message and exit</span>
</pre></div>
</div>
<p>需要注意的是，无论是从 <code class="docutils literal notranslate"><span class="pre">sys.argv[0]</span></code> 或是从 <code class="docutils literal notranslate"><span class="pre">prog=</span></code> 参数确定的程序名称，都可以在帮助消息里通过 <code class="docutils literal notranslate"><span class="pre">%(prog)s</span></code> 格式说明符来引用。</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;myprogram&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s1">&#39;foo of the </span><span class="si">%(prog)s</span><span class="s1"> program&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">print_help</span><span class="p">()</span>
<span class="go">usage: myprogram [-h] [--foo FOO]</span>

<span class="go">optional arguments:</span>
<span class="go"> -h, --help  show this help message and exit</span>
<span class="go"> --foo FOO   foo of the myprogram program</span>
</pre></div>
</div>
</div>
<div class="section" id="usage">
<h3>usage<a class="headerlink" href="#usage" title="永久链接至标题">¶</a></h3>
<p>默认情况下，<a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> 根据它包含的参数来构建用法消息：</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;PROG&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="s1">&#39;?&#39;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s1">&#39;foo help&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;bar&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="s1">&#39;+&#39;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s1">&#39;bar help&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">print_help</span><span class="p">()</span>
<span class="go">usage: PROG [-h] [--foo [FOO]] bar [bar ...]</span>

<span class="go">positional arguments:</span>
<span class="go"> bar          bar help</span>

<span class="go">optional arguments:</span>
<span class="go"> -h, --help   show this help message and exit</span>
<span class="go"> --foo [FOO]  foo help</span>
</pre></div>
</div>
<p>可以通过 <code class="docutils literal notranslate"><span class="pre">usage=</span></code> 关键字参数覆盖这一默认消息：</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;PROG&#39;</span><span class="p">,</span> <span class="n">usage</span><span class="o">=</span><span class="s1">&#39;</span><span class="si">%(prog)s</span><span class="s1"> [options]&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="s1">&#39;?&#39;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s1">&#39;foo help&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;bar&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="s1">&#39;+&#39;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s1">&#39;bar help&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">print_help</span><span class="p">()</span>
<span class="go">usage: PROG [options]</span>

<span class="go">positional arguments:</span>
<span class="go"> bar          bar help</span>

<span class="go">optional arguments:</span>
<span class="go"> -h, --help   show this help message and exit</span>
<span class="go"> --foo [FOO]  foo help</span>
</pre></div>
</div>
<p>在用法消息中可以使用 <code class="docutils literal notranslate"><span class="pre">%(prog)s</span></code> 格式说明符来填入程序名称。</p>
</div>
<div class="section" id="description">
<h3>描述<a class="headerlink" href="#description" title="永久链接至标题">¶</a></h3>
<p>大多数对 <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> 构造方法的调用都会使用 <code class="docutils literal notranslate"><span class="pre">description=</span></code> 关键字参数。这个参数简要描述这个程度做什么以及怎么做。在帮助消息中，这个描述会显示在命令行用法字符串和各种参数的帮助消息之间：</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">description</span><span class="o">=</span><span class="s1">&#39;A foo that bars&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">print_help</span><span class="p">()</span>
<span class="go">usage: argparse.py [-h]</span>

<span class="go">A foo that bars</span>

<span class="go">optional arguments:</span>
<span class="go"> -h, --help  show this help message and exit</span>
</pre></div>
</div>
<p>在默认情况下，description 将被换行以便适应给定的空间。如果想改变这种行为，见 <a class="reference internal" href="#formatter-class">formatter_class</a> 参数。</p>
</div>
<div class="section" id="epilog">
<h3>epilog<a class="headerlink" href="#epilog" title="永久链接至标题">¶</a></h3>
<p>一些程序喜欢在 description 参数后显示额外的对程序的描述。这种文字能够通过给 <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a>:: 提供 <code class="docutils literal notranslate"><span class="pre">epilog=</span></code> 参数而被指定。</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span>
<span class="gp">... </span>    <span class="n">description</span><span class="o">=</span><span class="s1">&#39;A foo that bars&#39;</span><span class="p">,</span>
<span class="gp">... </span>    <span class="n">epilog</span><span class="o">=</span><span class="s2">&quot;And that&#39;s how you&#39;d foo a bar&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">print_help</span><span class="p">()</span>
<span class="go">usage: argparse.py [-h]</span>

<span class="go">A foo that bars</span>

<span class="go">optional arguments:</span>
<span class="go"> -h, --help  show this help message and exit</span>

<span class="go">And that&#39;s how you&#39;d foo a bar</span>
</pre></div>
</div>
<p>和 <a class="reference internal" href="#description">description</a> 参数一样，<code class="docutils literal notranslate"><span class="pre">epilog=</span></code> text 在默认情况下会换行，但是这种行为能够被调整通过提供 <a class="reference internal" href="#formatter-class">formatter_class</a> 参数给 <code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParse</span></code>.</p>
</div>
<div class="section" id="parents">
<h3>parents<a class="headerlink" href="#parents" title="永久链接至标题">¶</a></h3>
<p>有些时候，少数解析器会使用同一系列参数。 单个解析器能够通过提供 <code class="docutils literal notranslate"><span class="pre">parents=</span></code> 参数给 <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> 而使用相同的参数而不是重复这些参数的定义。<code class="docutils literal notranslate"><span class="pre">parents=</span></code> 参数使用 <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> 对象的列表，从它们那里收集所有的位置和可选的行为，然后将这写行为加到正在构建的 <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> 对象。</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parent_parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">add_help</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parent_parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--parent&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">)</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">foo_parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">parents</span><span class="o">=</span><span class="p">[</span><span class="n">parent_parser</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">foo_parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;foo&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">foo_parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;--parent&#39;</span><span class="p">,</span> <span class="s1">&#39;2&#39;</span><span class="p">,</span> <span class="s1">&#39;XXX&#39;</span><span class="p">])</span>
<span class="go">Namespace(foo=&#39;XXX&#39;, parent=2)</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">bar_parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">parents</span><span class="o">=</span><span class="p">[</span><span class="n">parent_parser</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">bar_parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--bar&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">bar_parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;--bar&#39;</span><span class="p">,</span> <span class="s1">&#39;YYY&#39;</span><span class="p">])</span>
<span class="go">Namespace(bar=&#39;YYY&#39;, parent=None)</span>
</pre></div>
</div>
<p>请注意大多数父解析器会指定 <code class="docutils literal notranslate"><span class="pre">add_help=False</span></code> . 否则， <code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParse</span></code> 将会看到两个 <code class="docutils literal notranslate"><span class="pre">-h/--help</span></code> 选项（一个在父参数中一个在子参数中）并且产生一个错误。</p>
<div class="admonition note">
<p class="admonition-title">注解</p>
<p>你在传``parents=``给那些解析器时必须完全初始化它们。如果你在子解析器之后改变父解析器是，这些改变不会反映在子解析器上。</p>
</div>
</div>
<div class="section" id="formatter-class">
<h3>formatter_class<a class="headerlink" href="#formatter-class" title="永久链接至标题">¶</a></h3>
<p><a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> 对象允许通过指定备用格式化类来自定义帮助格式。目前，有四种这样的类。</p>
<dl class="class">
<dt id="argparse.RawDescriptionHelpFormatter">
<em class="property">class </em><code class="sig-prename descclassname">argparse.</code><code class="sig-name descname">RawDescriptionHelpFormatter</code><a class="headerlink" href="#argparse.RawDescriptionHelpFormatter" title="永久链接至目标">¶</a></dt>
<dt id="argparse.RawTextHelpFormatter">
<em class="property">class </em><code class="sig-prename descclassname">argparse.</code><code class="sig-name descname">RawTextHelpFormatter</code><a class="headerlink" href="#argparse.RawTextHelpFormatter" title="永久链接至目标">¶</a></dt>
<dt id="argparse.ArgumentDefaultsHelpFormatter">
<em class="property">class </em><code class="sig-prename descclassname">argparse.</code><code class="sig-name descname">ArgumentDefaultsHelpFormatter</code><a class="headerlink" href="#argparse.ArgumentDefaultsHelpFormatter" title="永久链接至目标">¶</a></dt>
<dt id="argparse.MetavarTypeHelpFormatter">
<em class="property">class </em><code class="sig-prename descclassname">argparse.</code><code class="sig-name descname">MetavarTypeHelpFormatter</code><a class="headerlink" href="#argparse.MetavarTypeHelpFormatter" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p><a class="reference internal" href="#argparse.RawDescriptionHelpFormatter" title="argparse.RawDescriptionHelpFormatter"><code class="xref py py-class docutils literal notranslate"><span class="pre">RawDescriptionHelpFormatter</span></code></a> 和 <a class="reference internal" href="#argparse.RawTextHelpFormatter" title="argparse.RawTextHelpFormatter"><code class="xref py py-class docutils literal notranslate"><span class="pre">RawTextHelpFormatter</span></code></a> 在正文的描述和展示上给与了更多的控制。<a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> 对象会将 <a class="reference internal" href="#description">description</a> 和 <a class="reference internal" href="#epilog">epilog</a> 的文字在命令行中自动换行。</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span>
<span class="gp">... </span>    <span class="n">prog</span><span class="o">=</span><span class="s1">&#39;PROG&#39;</span><span class="p">,</span>
<span class="gp">... </span>    <span class="n">description</span><span class="o">=</span><span class="s1">&#39;&#39;&#39;this description</span>
<span class="gp">... </span><span class="s1">        was indented weird</span>
<span class="gp">... </span><span class="s1">            but that is okay&#39;&#39;&#39;</span><span class="p">,</span>
<span class="gp">... </span>    <span class="n">epilog</span><span class="o">=</span><span class="s1">&#39;&#39;&#39;</span>
<span class="gp">... </span><span class="s1">            likewise for this epilog whose whitespace will</span>
<span class="gp">... </span><span class="s1">        be cleaned up and whose words will be wrapped</span>
<span class="gp">... </span><span class="s1">        across a couple lines&#39;&#39;&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">print_help</span><span class="p">()</span>
<span class="go">usage: PROG [-h]</span>

<span class="go">this description was indented weird but that is okay</span>

<span class="go">optional arguments:</span>
<span class="go"> -h, --help  show this help message and exit</span>

<span class="go">likewise for this epilog whose whitespace will be cleaned up and whose words</span>
<span class="go">will be wrapped across a couple lines</span>
</pre></div>
</div>
<p>传 <a class="reference internal" href="#argparse.RawDescriptionHelpFormatter" title="argparse.RawDescriptionHelpFormatter"><code class="xref py py-class docutils literal notranslate"><span class="pre">RawDescriptionHelpFormatter</span></code></a> 给 <code class="docutils literal notranslate"><span class="pre">formatter_class=</span></code> 表示 <a class="reference internal" href="#description">description</a> 和 <a class="reference internal" href="#epilog">epilog</a> 已经被正确的格式化了，不能在命令行中被自动换行:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span>
<span class="gp">... </span>    <span class="n">prog</span><span class="o">=</span><span class="s1">&#39;PROG&#39;</span><span class="p">,</span>
<span class="gp">... </span>    <span class="n">formatter_class</span><span class="o">=</span><span class="n">argparse</span><span class="o">.</span><span class="n">RawDescriptionHelpFormatter</span><span class="p">,</span>
<span class="gp">... </span>    <span class="n">description</span><span class="o">=</span><span class="n">textwrap</span><span class="o">.</span><span class="n">dedent</span><span class="p">(</span><span class="s1">&#39;&#39;&#39;</span><span class="se">\</span>
<span class="gp">... </span><span class="s1">        Please do not mess up this text!</span>
<span class="gp">... </span><span class="s1">        --------------------------------</span>
<span class="gp">... </span><span class="s1">            I have indented it</span>
<span class="gp">... </span><span class="s1">            exactly the way</span>
<span class="gp">... </span><span class="s1">            I want it</span>
<span class="gp">... </span><span class="s1">        &#39;&#39;&#39;</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">print_help</span><span class="p">()</span>
<span class="go">usage: PROG [-h]</span>

<span class="go">Please do not mess up this text!</span>
<span class="go">--------------------------------</span>
<span class="go">   I have indented it</span>
<span class="go">   exactly the way</span>
<span class="go">   I want it</span>

<span class="go">optional arguments:</span>
<span class="go"> -h, --help  show this help message and exit</span>
</pre></div>
</div>
<p><a class="reference internal" href="#argparse.RawTextHelpFormatter" title="argparse.RawTextHelpFormatter"><code class="xref py py-class docutils literal notranslate"><span class="pre">RawTextHelpFormatter</span></code></a> 保留所有种类文字的空格，包括参数的描述。然而，多重的新行会被替换成一行。如果你想保留多重的空白行，可以在新行之间加空格。</p>
<p><a class="reference internal" href="#argparse.ArgumentDefaultsHelpFormatter" title="argparse.ArgumentDefaultsHelpFormatter"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentDefaultsHelpFormatter</span></code></a> 自动添加默认的值的信息到每一个帮助信息的参数中:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span>
<span class="gp">... </span>    <span class="n">prog</span><span class="o">=</span><span class="s1">&#39;PROG&#39;</span><span class="p">,</span>
<span class="gp">... </span>    <span class="n">formatter_class</span><span class="o">=</span><span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentDefaultsHelpFormatter</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="mi">42</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s1">&#39;FOO!&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;bar&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="s1">&#39;*&#39;</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">],</span> <span class="n">help</span><span class="o">=</span><span class="s1">&#39;BAR!&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">print_help</span><span class="p">()</span>
<span class="go">usage: PROG [-h] [--foo FOO] [bar [bar ...]]</span>

<span class="go">positional arguments:</span>
<span class="go"> bar         BAR! (default: [1, 2, 3])</span>

<span class="go">optional arguments:</span>
<span class="go"> -h, --help  show this help message and exit</span>
<span class="go"> --foo FOO   FOO! (default: 42)</span>
</pre></div>
</div>
<p><a class="reference internal" href="#argparse.MetavarTypeHelpFormatter" title="argparse.MetavarTypeHelpFormatter"><code class="xref py py-class docutils literal notranslate"><span class="pre">MetavarTypeHelpFormatter</span></code></a> 为它的值在每一个参数中使用 <a class="reference internal" href="#type">type</a> 的参数名当作它的显示名（而不是使用通常的格式 <a class="reference internal" href="#dest">dest</a> ):</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span>
<span class="gp">... </span>    <span class="n">prog</span><span class="o">=</span><span class="s1">&#39;PROG&#39;</span><span class="p">,</span>
<span class="gp">... </span>    <span class="n">formatter_class</span><span class="o">=</span><span class="n">argparse</span><span class="o">.</span><span class="n">MetavarTypeHelpFormatter</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;bar&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">float</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">print_help</span><span class="p">()</span>
<span class="go">usage: PROG [-h] [--foo int] float</span>

<span class="go">positional arguments:</span>
<span class="go">  float</span>

<span class="go">optional arguments:</span>
<span class="go">  -h, --help  show this help message and exit</span>
<span class="go">  --foo int</span>
</pre></div>
</div>
</div>
<div class="section" id="prefix-chars">
<h3>prefix_chars<a class="headerlink" href="#prefix-chars" title="永久链接至标题">¶</a></h3>
<p>许多命令行会使用 <code class="docutils literal notranslate"><span class="pre">-</span></code> 当作前缀，比如 <code class="docutils literal notranslate"><span class="pre">-f/--foo</span></code>。如果解析器需要支持不同的或者额外的字符，比如像 <code class="docutils literal notranslate"><span class="pre">+f</span></code> 或者 <code class="docutils literal notranslate"><span class="pre">/foo</span></code> 的选项，可以在参数解析构建器中使用 <code class="docutils literal notranslate"><span class="pre">prefix_chars=</span></code> 参数。</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;PROG&#39;</span><span class="p">,</span> <span class="n">prefix_chars</span><span class="o">=</span><span class="s1">&#39;-+&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;+f&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;++bar&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="s1">&#39;+f X ++bar Y&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="go">Namespace(bar=&#39;Y&#39;, f=&#39;X&#39;)</span>
</pre></div>
</div>
<p>The <code class="docutils literal notranslate"><span class="pre">prefix_chars=</span></code> 参数默认使用 <code class="docutils literal notranslate"><span class="pre">'-'</span></code>. 支持一系列字符，但是不包括 <code class="docutils literal notranslate"><span class="pre">-</span></code> ，这样会产生不被允许的 <code class="docutils literal notranslate"><span class="pre">-f/--foo</span></code> 选项。</p>
</div>
<div class="section" id="fromfile-prefix-chars">
<h3>fromfile_prefix_chars<a class="headerlink" href="#fromfile-prefix-chars" title="永久链接至标题">¶</a></h3>
<p>有些时候，先举个例子，当处理一个特别长的参数列表的时候，把它存入一个文件中而不是在命令行打出来会很有意义。如果 <code class="docutils literal notranslate"><span class="pre">fromfile_prefix_chars=</span></code> 参数提供给 <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> 构造函数，之后所有类型的字符的参数都会被当成文件处理，并且会被文件包含的参数替代。举个栗子:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;args.txt&#39;</span><span class="p">,</span> <span class="s1">&#39;w&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">fp</span><span class="p">:</span>
<span class="gp">... </span>    <span class="n">fp</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s1">&#39;-f</span><span class="se">\n</span><span class="s1">bar&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">fromfile_prefix_chars</span><span class="o">=</span><span class="s1">&#39;@&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;-f&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;-f&#39;</span><span class="p">,</span> <span class="s1">&#39;foo&#39;</span><span class="p">,</span> <span class="s1">&#39;@args.txt&#39;</span><span class="p">])</span>
<span class="go">Namespace(f=&#39;bar&#39;)</span>
</pre></div>
</div>
<p>从文件读取的参数在默认情况下必须一个一行（但是可参见  <a class="reference internal" href="#argparse.ArgumentParser.convert_arg_line_to_args" title="argparse.ArgumentParser.convert_arg_line_to_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">convert_arg_line_to_args()</span></code></a>）并且它们被视为与命令行上的原始文件引用参数位于同一位置。所以在以上例子中，<code class="docutils literal notranslate"><span class="pre">['-f',</span> <span class="pre">'foo',</span> <span class="pre">'&#64;args.txt']</span></code> 的表示和 <code class="docutils literal notranslate"><span class="pre">['-f',</span> <span class="pre">'foo',</span> <span class="pre">'-f',</span> <span class="pre">'bar']</span></code> 的表示相同。</p>
<p><code class="docutils literal notranslate"><span class="pre">fromfile_prefix_chars=</span></code> 参数默认为 <code class="docutils literal notranslate"><span class="pre">None</span></code>，意味着参数不会被当作文件对待。</p>
</div>
<div class="section" id="argument-default">
<h3>argument_default<a class="headerlink" href="#argument-default" title="永久链接至标题">¶</a></h3>
<p>一般情况下，参数默认会通过设置一个默认到 <a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_argument()</span></code></a> 或者调用带一组指定键值对的 <a class="reference internal" href="#argparse.ArgumentParser.set_defaults" title="argparse.ArgumentParser.set_defaults"><code class="xref py py-meth docutils literal notranslate"><span class="pre">ArgumentParser.set_defaults()</span></code></a> 方法。但是有些时候，为参数指定一个普遍适用的解析器会更有用。这能够通过传输 <code class="docutils literal notranslate"><span class="pre">argument_default=</span></code> 关键词参数给 <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> 来完成。举个栗子，要全局禁止在 <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code></a> 中创建属性，我们提供 <code class="docutils literal notranslate"><span class="pre">argument_default=SUPPRESS</span></code>:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">argument_default</span><span class="o">=</span><span class="n">argparse</span><span class="o">.</span><span class="n">SUPPRESS</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;bar&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="s1">&#39;?&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="s1">&#39;1&#39;</span><span class="p">,</span> <span class="s1">&#39;BAR&#39;</span><span class="p">])</span>
<span class="go">Namespace(bar=&#39;BAR&#39;, foo=&#39;1&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([])</span>
<span class="go">Namespace()</span>
</pre></div>
</div>
</div>
<div class="section" id="allow-abbrev">
<span id="id1"></span><h3>allow_abbrev<a class="headerlink" href="#allow-abbrev" title="永久链接至标题">¶</a></h3>
<p>正常情况下，当你向 <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> 的 <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code></a> 方法传入一个参数列表时，它会 <a class="reference internal" href="#prefix-matching"><span class="std std-ref">recognizes abbreviations</span></a>。</p>
<p>这个特性可以设置 <code class="docutils literal notranslate"><span class="pre">allow_abbrev</span></code> 为 <code class="docutils literal notranslate"><span class="pre">False</span></code> 来关闭:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;PROG&#39;</span><span class="p">,</span> <span class="n">allow_abbrev</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foobar&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;store_true&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foonley&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;store_false&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;--foon&#39;</span><span class="p">])</span>
<span class="go">usage: PROG [-h] [--foobar] [--foonley]</span>
<span class="go">PROG: error: unrecognized arguments: --foon</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified added">3.5 新版功能.</span></p>
</div>
</div>
<div class="section" id="conflict-handler">
<h3>conflict_handler<a class="headerlink" href="#conflict-handler" title="永久链接至标题">¶</a></h3>
<p><a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> 对象不允许在相同选项字符串下有两种行为。默认情况下， <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> 对象会产生一个异常如果去创建一个正在使用的选项字符串参数。</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;PROG&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;-f&#39;</span><span class="p">,</span> <span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s1">&#39;old foo help&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s1">&#39;new foo help&#39;</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
<span class="gr"> ..</span>
<span class="gr">ArgumentError</span>: <span class="n">argument --foo: conflicting option string(s): --foo</span>
</pre></div>
</div>
<p>有些时候（例如：使用 <a class="reference internal" href="#parents">parents</a>），重写旧的有相同选项字符串的参数会更有用。为了产生这种行为， <code class="docutils literal notranslate"><span class="pre">'resolve'</span></code> 值可以提供给 <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> 的 <code class="docutils literal notranslate"><span class="pre">conflict_handler=</span></code> 参数:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;PROG&#39;</span><span class="p">,</span> <span class="n">conflict_handler</span><span class="o">=</span><span class="s1">&#39;resolve&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;-f&#39;</span><span class="p">,</span> <span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s1">&#39;old foo help&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s1">&#39;new foo help&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">print_help</span><span class="p">()</span>
<span class="go">usage: PROG [-h] [-f FOO] [--foo FOO]</span>

<span class="go">optional arguments:</span>
<span class="go"> -h, --help  show this help message and exit</span>
<span class="go"> -f FOO      old foo help</span>
<span class="go"> --foo FOO   new foo help</span>
</pre></div>
</div>
<p>注意 <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> 对象只能移除一个行为如果它所有的选项字符串都被重写。所以，在上面的例子中，旧的 <code class="docutils literal notranslate"><span class="pre">-f/--foo</span></code> 行为 回合 <code class="docutils literal notranslate"><span class="pre">-f</span></code> 行为保持一样, 因为只有 <code class="docutils literal notranslate"><span class="pre">--foo</span></code> 选项字符串被重写。</p>
</div>
<div class="section" id="add-help">
<h3>add_help<a class="headerlink" href="#add-help" title="永久链接至标题">¶</a></h3>
<p>默认情况下，ArgumentParser 对象添加一个简单的显示解析器帮助信息的选项。举个栗子，考虑一个名为 <code class="docutils literal notranslate"><span class="pre">myprogram.py</span></code> 的文件包含如下代码:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">argparse</span>
<span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s1">&#39;foo help&#39;</span><span class="p">)</span>
<span class="n">args</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">()</span>
</pre></div>
</div>
<p>如果 <code class="docutils literal notranslate"><span class="pre">-h</span></code> or <code class="docutils literal notranslate"><span class="pre">--help</span></code> 在命令行中被提供, 参数解析器帮助信息会打印:</p>
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$</span> python myprogram.py --help
<span class="go">usage: myprogram.py [-h] [--foo FOO]</span>

<span class="go">optional arguments:</span>
<span class="go"> -h, --help  show this help message and exit</span>
<span class="go"> --foo FOO   foo help</span>
</pre></div>
</div>
<p>有时候可能会需要关闭额外的帮助信息。这可以通过在 <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> 中设置 <code class="docutils literal notranslate"><span class="pre">add_help=</span></code> 参数为 <code class="docutils literal notranslate"><span class="pre">False</span></code> 来实现。</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;PROG&#39;</span><span class="p">,</span> <span class="n">add_help</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s1">&#39;foo help&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">print_help</span><span class="p">()</span>
<span class="go">usage: PROG [--foo FOO]</span>

<span class="go">optional arguments:</span>
<span class="go"> --foo FOO  foo help</span>
</pre></div>
</div>
<p>帮助选项一般为 <code class="docutils literal notranslate"><span class="pre">-h/--help</span></code>。如果 <code class="docutils literal notranslate"><span class="pre">prefix_chars=</span></code> 被指定并且没有包含 <code class="docutils literal notranslate"><span class="pre">-</span></code> 字符，在这种情况下， <code class="docutils literal notranslate"><span class="pre">-h</span></code> <code class="docutils literal notranslate"><span class="pre">--help</span></code> 不是有效的选项。此时， <code class="docutils literal notranslate"><span class="pre">prefix_chars</span></code> 的第一个字符将用作帮助选项的前缀。</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;PROG&#39;</span><span class="p">,</span> <span class="n">prefix_chars</span><span class="o">=</span><span class="s1">&#39;+/&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">print_help</span><span class="p">()</span>
<span class="go">usage: PROG [+h]</span>

<span class="go">optional arguments:</span>
<span class="go">  +h, ++help  show this help message and exit</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="the-add-argument-method">
<h2>add_argument() 方法<a class="headerlink" href="#the-add-argument-method" title="永久链接至标题">¶</a></h2>
<dl class="method">
<dt id="argparse.ArgumentParser.add_argument">
<code class="sig-prename descclassname">ArgumentParser.</code><code class="sig-name descname">add_argument</code><span class="sig-paren">(</span><em class="sig-param">name or flags...</em><span class="optional">[</span>, <em class="sig-param">action</em><span class="optional">]</span><span class="optional">[</span>, <em class="sig-param">nargs</em><span class="optional">]</span><span class="optional">[</span>, <em class="sig-param">const</em><span class="optional">]</span><span class="optional">[</span>, <em class="sig-param">default</em><span class="optional">]</span><span class="optional">[</span>, <em class="sig-param">type</em><span class="optional">]</span><span class="optional">[</span>, <em class="sig-param">choices</em><span class="optional">]</span><span class="optional">[</span>, <em class="sig-param">required</em><span class="optional">]</span><span class="optional">[</span>, <em class="sig-param">help</em><span class="optional">]</span><span class="optional">[</span>, <em class="sig-param">metavar</em><span class="optional">]</span><span class="optional">[</span>, <em class="sig-param">dest</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#argparse.ArgumentParser.add_argument" title="永久链接至目标">¶</a></dt>
<dd><p>定义单个的命令行参数应当如何解析。每个形参都在下面有它自己更多的描述，长话短说有：</p>
<ul class="simple">
<li><p><a class="reference internal" href="#name-or-flags">name or flags</a> - 一个命名或者一个选项字符串的列表，例如 <code class="docutils literal notranslate"><span class="pre">foo</span></code> 或 <code class="docutils literal notranslate"><span class="pre">-f,</span> <span class="pre">--foo</span></code>。</p></li>
<li><p><a class="reference internal" href="#action">action</a> - 当参数在命令行中出现时使用的动作基本类型。</p></li>
<li><p><a class="reference internal" href="#nargs">nargs</a> - 命令行参数应当消耗的数目。</p></li>
<li><p><a class="reference internal" href="#const">const</a> - 被一些 <a class="reference internal" href="#action">action</a> 和 <a class="reference internal" href="#nargs">nargs</a> 选择所需求的常数。</p></li>
<li><p><a class="reference internal" href="#default">default</a> - 当参数未在命令行中出现时使用的值。</p></li>
<li><p><a class="reference internal" href="#type">type</a> - 命令行参数应当被转换成的类型。</p></li>
<li><p><a class="reference internal" href="#choices">choices</a> - 可用的参数的容器。</p></li>
<li><p><a class="reference internal" href="#required">required</a> - 此命令行选项是否可省略 （仅选项可用）。</p></li>
<li><p><a class="reference internal" href="#help">help</a> - 一个此选项作用的简单描述。</p></li>
<li><p><a class="reference internal" href="#metavar">metavar</a> - 在使用方法消息中使用的参数值示例。</p></li>
<li><p><a class="reference internal" href="#dest">dest</a> - 被添加到 <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code></a> 所返回对象上的属性名。</p></li>
</ul>
</dd></dl>

<p>以下部分描述这些参数如何使用。</p>
<div class="section" id="name-or-flags">
<h3>name or flags<a class="headerlink" href="#name-or-flags" title="永久链接至标题">¶</a></h3>
<p><a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_argument()</span></code></a> 方法必须知道它是否是一个选项，例如 <code class="docutils literal notranslate"><span class="pre">-f</span></code> 或 <code class="docutils literal notranslate"><span class="pre">--foo</span></code>，或是一个位置参数，例如一组文件名。第一个传递给 <a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_argument()</span></code></a> 的参数必须是一系列 flags 或者是一个简单的参数名。例如，可以选项可以被这样创建:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;-f&#39;</span><span class="p">,</span> <span class="s1">&#39;--foo&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>而位置参数可以这么创建:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;bar&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>当 <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code></a> 被调用，选项会以 <code class="docutils literal notranslate"><span class="pre">-</span></code> 前缀识别，剩下的参数则会被假定为位置参数:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;PROG&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;-f&#39;</span><span class="p">,</span> <span class="s1">&#39;--foo&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;bar&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;BAR&#39;</span><span class="p">])</span>
<span class="go">Namespace(bar=&#39;BAR&#39;, foo=None)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;BAR&#39;</span><span class="p">,</span> <span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="s1">&#39;FOO&#39;</span><span class="p">])</span>
<span class="go">Namespace(bar=&#39;BAR&#39;, foo=&#39;FOO&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="s1">&#39;FOO&#39;</span><span class="p">])</span>
<span class="go">usage: PROG [-h] [-f FOO] bar</span>
<span class="go">PROG: error: the following arguments are required: bar</span>
</pre></div>
</div>
</div>
<div class="section" id="action">
<h3>action<a class="headerlink" href="#action" title="永久链接至标题">¶</a></h3>
<p><a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> 对象将命令行参数与动作相关联。这些动作可以做与它们相关联的命令行参数的任何事，尽管大多数动作只是简单的向 <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code></a> 返回的对象上添加属性。<code class="docutils literal notranslate"><span class="pre">action</span></code> 命名参数指定了这个命令行参数应当如何处理。供应的动作有：</p>
<ul>
<li><p><code class="docutils literal notranslate"><span class="pre">'store'</span></code> - 存储参数的值。这是默认的动作。例如:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="s1">&#39;--foo 1&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="go">Namespace(foo=&#39;1&#39;)</span>
</pre></div>
</div>
</li>
<li><p><code class="docutils literal notranslate"><span class="pre">'store_const'</span></code> - 存储被 <a class="reference internal" href="#const">const</a> 命名参数指定的值。 <code class="docutils literal notranslate"><span class="pre">'store_const'</span></code> 动作通常用在选项中来指定一些标志。例如:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;store_const&#39;</span><span class="p">,</span> <span class="n">const</span><span class="o">=</span><span class="mi">42</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;--foo&#39;</span><span class="p">])</span>
<span class="go">Namespace(foo=42)</span>
</pre></div>
</div>
</li>
<li><p><code class="docutils literal notranslate"><span class="pre">'store_true'</span></code> and <code class="docutils literal notranslate"><span class="pre">'store_false'</span></code> - 这些是 <code class="docutils literal notranslate"><span class="pre">'store_const'</span></code> 分别用作存储 <code class="docutils literal notranslate"><span class="pre">True</span></code> 和 <code class="docutils literal notranslate"><span class="pre">False</span></code> 值的特殊用例。另外，它们的默认值分别为 <code class="docutils literal notranslate"><span class="pre">False</span></code> 和 <code class="docutils literal notranslate"><span class="pre">True</span></code>。例如:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;store_true&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--bar&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;store_false&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--baz&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;store_false&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="s1">&#39;--foo --bar&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="go">Namespace(foo=True, bar=False, baz=True)</span>
</pre></div>
</div>
</li>
<li><p><code class="docutils literal notranslate"><span class="pre">'append'</span></code> - 存储一个列表，并且将每个参数值追加到列表中。在允许多次使用选项时很有用。例如:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;append&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="s1">&#39;--foo 1 --foo 2&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="go">Namespace(foo=[&#39;1&#39;, &#39;2&#39;])</span>
</pre></div>
</div>
</li>
<li><p><code class="docutils literal notranslate"><span class="pre">'append_const'</span></code> - 这存储一个列表，并将 <a class="reference internal" href="#const">const</a> 命名参数指定的值追加到列表中。（注意 <a class="reference internal" href="#const">const</a> 命名参数默认为 <code class="docutils literal notranslate"><span class="pre">None</span></code>。）``'append_const'`` 动作一般在多个参数需要在同一列表中存储常数时会有用。例如:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--str&#39;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s1">&#39;types&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;append_const&#39;</span><span class="p">,</span> <span class="n">const</span><span class="o">=</span><span class="nb">str</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--int&#39;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s1">&#39;types&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;append_const&#39;</span><span class="p">,</span> <span class="n">const</span><span class="o">=</span><span class="nb">int</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="s1">&#39;--str --int&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="go">Namespace(types=[&lt;class &#39;str&#39;&gt;, &lt;class &#39;int&#39;&gt;])</span>
</pre></div>
</div>
</li>
<li><p><code class="docutils literal notranslate"><span class="pre">'count'</span></code> - 计算一个关键字参数出现的数目或次数。例如，对于一个增长的详情等级来说有用:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--verbose&#39;</span><span class="p">,</span> <span class="s1">&#39;-v&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;count&#39;</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;-vvv&#39;</span><span class="p">])</span>
<span class="go">Namespace(verbose=3)</span>
</pre></div>
</div>
<p>请注意，<em>default</em> 将为 <code class="docutils literal notranslate"><span class="pre">None</span></code>，除非显式地设为 <em>0</em>。</p>
</li>
<li><p><code class="docutils literal notranslate"><span class="pre">'help'</span></code> - 打印所有当前解析器中的选项和参数的完整帮助信息，然后退出。默认情况下，一个 help 动作会被自动加入解析器。关于输出是如何创建的，参与 <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a>。</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">'version'</span></code> - 期望有一个 <code class="docutils literal notranslate"><span class="pre">version=</span></code> 命名参数在 <a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_argument()</span></code></a> 调用中，并打印版本信息并在调用后退出:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">argparse</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;PROG&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--version&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;version&#39;</span><span class="p">,</span> <span class="n">version</span><span class="o">=</span><span class="s1">&#39;</span><span class="si">%(prog)s</span><span class="s1"> 2.0&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;--version&#39;</span><span class="p">])</span>
<span class="go">PROG 2.0</span>
</pre></div>
</div>
</li>
</ul>
<p>您还可以通过传递 Action 子类或实现相同接口的其他对象来指定任意操作。建议的方法是扩展 <a class="reference internal" href="#argparse.Action" title="argparse.Action"><code class="xref py py-class docutils literal notranslate"><span class="pre">Action</span></code></a>，覆盖 <code class="docutils literal notranslate"><span class="pre">__call__</span></code> 方法和可选的 <code class="docutils literal notranslate"><span class="pre">__init__</span></code> 方法。</p>
<p>一个自定义动作的例子:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">FooAction</span><span class="p">(</span><span class="n">argparse</span><span class="o">.</span><span class="n">Action</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">option_strings</span><span class="p">,</span> <span class="n">dest</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
<span class="gp">... </span>        <span class="k">if</span> <span class="n">nargs</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
<span class="gp">... </span>            <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span><span class="s2">&quot;nargs not allowed&quot;</span><span class="p">)</span>
<span class="gp">... </span>        <span class="nb">super</span><span class="p">(</span><span class="n">FooAction</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="fm">__init__</span><span class="p">(</span><span class="n">option_strings</span><span class="p">,</span> <span class="n">dest</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="fm">__call__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">parser</span><span class="p">,</span> <span class="n">namespace</span><span class="p">,</span> <span class="n">values</span><span class="p">,</span> <span class="n">option_string</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
<span class="gp">... </span>        <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;</span><span class="si">%r</span><span class="s1"> </span><span class="si">%r</span><span class="s1"> </span><span class="si">%r</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="p">(</span><span class="n">namespace</span><span class="p">,</span> <span class="n">values</span><span class="p">,</span> <span class="n">option_string</span><span class="p">))</span>
<span class="gp">... </span>        <span class="nb">setattr</span><span class="p">(</span><span class="n">namespace</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">dest</span><span class="p">,</span> <span class="n">values</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="n">FooAction</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;bar&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="n">FooAction</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">args</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="s1">&#39;1 --foo 2&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="go">Namespace(bar=None, foo=None) &#39;1&#39; None</span>
<span class="go">Namespace(bar=&#39;1&#39;, foo=None) &#39;2&#39; &#39;--foo&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">args</span>
<span class="go">Namespace(bar=&#39;1&#39;, foo=&#39;2&#39;)</span>
</pre></div>
</div>
<p>更多描述，见 <a class="reference internal" href="#argparse.Action" title="argparse.Action"><code class="xref py py-class docutils literal notranslate"><span class="pre">Action</span></code></a>。</p>
</div>
<div class="section" id="nargs">
<h3>nargs<a class="headerlink" href="#nargs" title="永久链接至标题">¶</a></h3>
<p>ArgumentParser 对象通常关联一个单独的命令行参数到一个单独的被执行的动作。 <code class="docutils literal notranslate"><span class="pre">nargs</span></code> 命名参数关联不同数目的命令行参数到单一动作。支持的值有：</p>
<ul>
<li><p><code class="docutils literal notranslate"><span class="pre">N</span></code> （一个整数）。命令行中的 <code class="docutils literal notranslate"><span class="pre">N</span></code> 个参数会被聚集到一个列表中。 例如:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="mi">2</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;bar&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="s1">&#39;c --foo a b&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="go">Namespace(bar=[&#39;c&#39;], foo=[&#39;a&#39;, &#39;b&#39;])</span>
</pre></div>
</div>
<p>注意 <code class="docutils literal notranslate"><span class="pre">nargs=1</span></code> 会产生一个单元素列表。这和默认的元素本身是不同的。</p>
</li>
</ul>
<ul id="index-0">
<li><p><code class="docutils literal notranslate"><span class="pre">'?'</span></code>。如果可能的话，会从命令行中消耗一个参数，并产生一个单一项。如果当前没有命令行参数，则会产生 <a class="reference internal" href="#default">default</a> 值。注意，对于选项，有另外的用例 - 选项字符串出现但没有跟随命令行参数，则会产生 <a class="reference internal" href="#const">const</a> 值。一些说用用例:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="s1">&#39;?&#39;</span><span class="p">,</span> <span class="n">const</span><span class="o">=</span><span class="s1">&#39;c&#39;</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="s1">&#39;d&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;bar&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="s1">&#39;?&#39;</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="s1">&#39;d&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;XX&#39;</span><span class="p">,</span> <span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="s1">&#39;YY&#39;</span><span class="p">])</span>
<span class="go">Namespace(bar=&#39;XX&#39;, foo=&#39;YY&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;XX&#39;</span><span class="p">,</span> <span class="s1">&#39;--foo&#39;</span><span class="p">])</span>
<span class="go">Namespace(bar=&#39;XX&#39;, foo=&#39;c&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([])</span>
<span class="go">Namespace(bar=&#39;d&#39;, foo=&#39;d&#39;)</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">nargs='?'</span></code> 的一个更普遍用法是允许可选的输入或输出文件:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;infile&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="s1">&#39;?&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="n">argparse</span><span class="o">.</span><span class="n">FileType</span><span class="p">(</span><span class="s1">&#39;r&#39;</span><span class="p">),</span>
<span class="gp">... </span>                    <span class="n">default</span><span class="o">=</span><span class="n">sys</span><span class="o">.</span><span class="n">stdin</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;outfile&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="s1">&#39;?&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="n">argparse</span><span class="o">.</span><span class="n">FileType</span><span class="p">(</span><span class="s1">&#39;w&#39;</span><span class="p">),</span>
<span class="gp">... </span>                    <span class="n">default</span><span class="o">=</span><span class="n">sys</span><span class="o">.</span><span class="n">stdout</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;input.txt&#39;</span><span class="p">,</span> <span class="s1">&#39;output.txt&#39;</span><span class="p">])</span>
<span class="go">Namespace(infile=&lt;_io.TextIOWrapper name=&#39;input.txt&#39; encoding=&#39;UTF-8&#39;&gt;,</span>
<span class="go">          outfile=&lt;_io.TextIOWrapper name=&#39;output.txt&#39; encoding=&#39;UTF-8&#39;&gt;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([])</span>
<span class="go">Namespace(infile=&lt;_io.TextIOWrapper name=&#39;&lt;stdin&gt;&#39; encoding=&#39;UTF-8&#39;&gt;,</span>
<span class="go">          outfile=&lt;_io.TextIOWrapper name=&#39;&lt;stdout&gt;&#39; encoding=&#39;UTF-8&#39;&gt;)</span>
</pre></div>
</div>
</li>
</ul>
<ul id="index-1">
<li><p><code class="docutils literal notranslate"><span class="pre">'*'</span></code>。所有当前命令行参数被聚集到一个列表中。注意通过 <code class="docutils literal notranslate"><span class="pre">nargs='*'</span></code> 来实现多个位置参数通常没有意义，但是多个选项是可能的。例如:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="s1">&#39;*&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--bar&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="s1">&#39;*&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;baz&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="s1">&#39;*&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="s1">&#39;a b --foo x y --bar 1 2&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="go">Namespace(bar=[&#39;1&#39;, &#39;2&#39;], baz=[&#39;a&#39;, &#39;b&#39;], foo=[&#39;x&#39;, &#39;y&#39;])</span>
</pre></div>
</div>
</li>
</ul>
<ul id="index-2">
<li><p><code class="docutils literal notranslate"><span class="pre">'+'</span></code>。和 <code class="docutils literal notranslate"><span class="pre">'*'</span></code> 类似，所有当前命令行参数被聚集到一个列表中。另外，当前没有至少一个命令行参数时会产生一个错误信息。例如:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;PROG&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;foo&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="s1">&#39;+&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="s1">&#39;b&#39;</span><span class="p">])</span>
<span class="go">Namespace(foo=[&#39;a&#39;, &#39;b&#39;])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([])</span>
<span class="go">usage: PROG [-h] foo [foo ...]</span>
<span class="go">PROG: error: the following arguments are required: foo</span>
</pre></div>
</div>
</li>
</ul>
<ul id="argparse-remainder">
<li><p><code class="docutils literal notranslate"><span class="pre">argarse.REMAINDER</span></code>。所有剩余的命令行参数被聚集到一个列表中。这通常在从一个命令行功能传递参数到另一个命令行功能中时有用:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;PROG&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;command&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;args&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="n">argparse</span><span class="o">.</span><span class="n">REMAINDER</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="s1">&#39;--foo B cmd --arg1 XX ZZ&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">()))</span>
<span class="go">Namespace(args=[&#39;--arg1&#39;, &#39;XX&#39;, &#39;ZZ&#39;], command=&#39;cmd&#39;, foo=&#39;B&#39;)</span>
</pre></div>
</div>
</li>
</ul>
<p>如果不提供 <code class="docutils literal notranslate"><span class="pre">nargs</span></code> 命名参数，则消耗参数的数目将被 <a class="reference internal" href="#action">action</a> 决定。通常这意味着单一项目（非列表）消耗单一命令行参数。</p>
</div>
<div class="section" id="const">
<h3>const<a class="headerlink" href="#const" title="永久链接至标题">¶</a></h3>
<p><a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_argument()</span></code></a>  的``const`` 参数用于保存不从命令行中读取但被各种 <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> 动作需求的常数值。最常用的两例为：</p>
<ul class="simple">
<li><p>当 <a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_argument()</span></code></a> 通过 <code class="docutils literal notranslate"><span class="pre">action='store_const'</span></code> 或 <code class="docutils literal notranslate"><span class="pre">action='append_const</span></code> 调用时。这些动作将 <code class="docutils literal notranslate"><span class="pre">const</span></code> 值添加到 <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code></a> 返回的对象的属性中。在 <a class="reference internal" href="#action">action</a> 的描述中查看案例。</p></li>
<li><p>当 <a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_argument()</span></code></a> 通过选项（例如 <code class="docutils literal notranslate"><span class="pre">-f</span></code> 或 <code class="docutils literal notranslate"><span class="pre">--foo</span></code>）调用并且 <code class="docutils literal notranslate"><span class="pre">nargs='?'</span></code> 时。这会创建一个可以跟随零个或一个命令行参数的选项。当解析命令行时，如果选项后没有参数，则将用 <code class="docutils literal notranslate"><span class="pre">const</span></code> 代替。在 <a class="reference internal" href="#nargs">nargs</a> 描述中查看案例。</p></li>
</ul>
<p>对 <code class="docutils literal notranslate"><span class="pre">'store_const'</span></code> 和 <code class="docutils literal notranslate"><span class="pre">'append_const'</span></code> 动作， <code class="docutils literal notranslate"><span class="pre">const</span></code> 命名参数必须给出。对其他动作，默认为 <code class="docutils literal notranslate"><span class="pre">None</span></code>。</p>
</div>
<div class="section" id="default">
<h3>默认值<a class="headerlink" href="#default" title="永久链接至标题">¶</a></h3>
<p>所有选项和一些位置参数可能在命令行中被忽略。<a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_argument()</span></code></a> 的命名参数 <code class="docutils literal notranslate"><span class="pre">default</span></code>，默认值为 <code class="docutils literal notranslate"><span class="pre">None</span></code>，指定了在命令行参数未出现时应当使用的值。对于选项， <code class="docutils literal notranslate"><span class="pre">default</span></code> 值在选项未在命令行中出现时使用:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="mi">42</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="s1">&#39;2&#39;</span><span class="p">])</span>
<span class="go">Namespace(foo=&#39;2&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([])</span>
<span class="go">Namespace(foo=42)</span>
</pre></div>
</div>
<p>如果 <code class="docutils literal notranslate"><span class="pre">default</span></code> 值是一个字符串，解析器解析此值就像一个命令行参数。特别是，在将属性设置在 <a class="reference internal" href="#argparse.Namespace" title="argparse.Namespace"><code class="xref py py-class docutils literal notranslate"><span class="pre">Namespace</span></code></a> 的返回值之前，解析器应用任何提供的 <a class="reference internal" href="#type">type</a> 转换参数。否则解析器使用原值:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--length&#39;</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="s1">&#39;10&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--width&#39;</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="mf">10.5</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">()</span>
<span class="go">Namespace(length=10, width=10.5)</span>
</pre></div>
</div>
<p>对于 <a class="reference internal" href="#nargs">nargs</a> 等于 <code class="docutils literal notranslate"><span class="pre">?</span></code> 或 <code class="docutils literal notranslate"><span class="pre">*</span></code> 的位置参数， <code class="docutils literal notranslate"><span class="pre">default</span></code> 值在没有命令行参数出现时使用。</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;foo&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="s1">&#39;?&#39;</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="mi">42</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;a&#39;</span><span class="p">])</span>
<span class="go">Namespace(foo=&#39;a&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([])</span>
<span class="go">Namespace(foo=42)</span>
</pre></div>
</div>
<p>提供 <code class="docutils literal notranslate"><span class="pre">default=argparse.SUPPRESS</span></code> 导致命令行参数未出现时没有属性被添加:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="n">argparse</span><span class="o">.</span><span class="n">SUPPRESS</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([])</span>
<span class="go">Namespace()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="s1">&#39;1&#39;</span><span class="p">])</span>
<span class="go">Namespace(foo=&#39;1&#39;)</span>
</pre></div>
</div>
</div>
<div class="section" id="type">
<h3>type -- 类型<a class="headerlink" href="#type" title="永久链接至标题">¶</a></h3>
<p>默认情况下，<a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> 对象将命令行参数当作简单字符串读入。然而，命令行字符串经常需要被当作其它的类型，比如 <a class="reference internal" href="functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a> 或者 <a class="reference internal" href="functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a>。<a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_argument()</span></code></a> 的 <code class="docutils literal notranslate"><span class="pre">type</span></code> 关键词参数允许任何的类型检查和类型转换。一般的内建类型和函数可以直接被 <code class="docutils literal notranslate"><span class="pre">type</span></code> 参数使用。</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;foo&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;bar&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">open</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="s1">&#39;2 temp.txt&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="go">Namespace(bar=&lt;_io.TextIOWrapper name=&#39;temp.txt&#39; encoding=&#39;UTF-8&#39;&gt;, foo=2)</span>
</pre></div>
</div>
<p>当 <code class="docutils literal notranslate"><span class="pre">type</span></code> 参数被应用到默认参数时，请参考 <a class="reference internal" href="#default">default</a> 参数的部分。</p>
<p>为方便使用不同类型的文件，argparse 模块提供了 FileType 工厂类，该类接受 <code class="docutils literal notranslate"><span class="pre">mode=</span></code>, <code class="docutils literal notranslate"><span class="pre">bufsize=</span></code>, <code class="docutils literal notranslate"><span class="pre">encoding=</span></code> 和 <code class="docutils literal notranslate"><span class="pre">errors=</span></code> 等 <a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> 函数参数。 例如，<code class="docutils literal notranslate"><span class="pre">FileType('w')</span></code> 可被用来创建一个可写文件:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;bar&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="n">argparse</span><span class="o">.</span><span class="n">FileType</span><span class="p">(</span><span class="s1">&#39;w&#39;</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;out.txt&#39;</span><span class="p">])</span>
<span class="go">Namespace(bar=&lt;_io.TextIOWrapper name=&#39;out.txt&#39; encoding=&#39;UTF-8&#39;&gt;)</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">type=</span></code> 可接受任意可调用对象，该对象应传入单个字符串参数并返回转换后的值:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">perfect_square</span><span class="p">(</span><span class="n">string</span><span class="p">):</span>
<span class="gp">... </span>    <span class="n">value</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">string</span><span class="p">)</span>
<span class="gp">... </span>    <span class="n">sqrt</span> <span class="o">=</span> <span class="n">math</span><span class="o">.</span><span class="n">sqrt</span><span class="p">(</span><span class="n">value</span><span class="p">)</span>
<span class="gp">... </span>    <span class="k">if</span> <span class="n">sqrt</span> <span class="o">!=</span> <span class="nb">int</span><span class="p">(</span><span class="n">sqrt</span><span class="p">):</span>
<span class="gp">... </span>        <span class="n">msg</span> <span class="o">=</span> <span class="s2">&quot;</span><span class="si">%r</span><span class="s2"> is not a perfect square&quot;</span> <span class="o">%</span> <span class="n">string</span>
<span class="gp">... </span>        <span class="k">raise</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentTypeError</span><span class="p">(</span><span class="n">msg</span><span class="p">)</span>
<span class="gp">... </span>    <span class="k">return</span> <span class="n">value</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;PROG&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;foo&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="n">perfect_square</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;9&#39;</span><span class="p">])</span>
<span class="go">Namespace(foo=9)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;7&#39;</span><span class="p">])</span>
<span class="go">usage: PROG [-h] foo</span>
<span class="go">PROG: error: argument foo: &#39;7&#39; is not a perfect square</span>
</pre></div>
</div>
<p><a class="reference internal" href="#choices">choices</a> 关键词参数可能会使类型检查者更方便的检查一个范围的值。</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;PROG&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;foo&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">,</span> <span class="n">choices</span><span class="o">=</span><span class="nb">range</span><span class="p">(</span><span class="mi">5</span><span class="p">,</span> <span class="mi">10</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;7&#39;</span><span class="p">])</span>
<span class="go">Namespace(foo=7)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;11&#39;</span><span class="p">])</span>
<span class="go">usage: PROG [-h] {5,6,7,8,9}</span>
<span class="go">PROG: error: argument foo: invalid choice: 11 (choose from 5, 6, 7, 8, 9)</span>
</pre></div>
</div>
<p>详情请查阅 <a class="reference internal" href="#choices">choices</a> 段落。</p>
</div>
<div class="section" id="choices">
<h3>choices<a class="headerlink" href="#choices" title="永久链接至标题">¶</a></h3>
<p>某些命令行参数应当从一组受限值中选择。 这可通过将一个容器对象作为 <em>choices</em> 关键字参数传给 <a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_argument()</span></code></a> 来处理。 当执行命令行解析时，参数值将被检查，如果参数不是可接受的值之一就将显示错误消息:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;game.py&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;move&#39;</span><span class="p">,</span> <span class="n">choices</span><span class="o">=</span><span class="p">[</span><span class="s1">&#39;rock&#39;</span><span class="p">,</span> <span class="s1">&#39;paper&#39;</span><span class="p">,</span> <span class="s1">&#39;scissors&#39;</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;rock&#39;</span><span class="p">])</span>
<span class="go">Namespace(move=&#39;rock&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;fire&#39;</span><span class="p">])</span>
<span class="go">usage: game.py [-h] {rock,paper,scissors}</span>
<span class="go">game.py: error: argument move: invalid choice: &#39;fire&#39; (choose from &#39;rock&#39;,</span>
<span class="go">&#39;paper&#39;, &#39;scissors&#39;)</span>
</pre></div>
</div>
<p>请注意 <em>choices</em> 容器包含的内容会在执行任意 <a class="reference internal" href="#type">type</a> 转换之后被检查，因此 <em>choices</em> 容器中对象的类型应当与指定的 <a class="reference internal" href="#type">type</a> 相匹配:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;doors.py&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;door&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">,</span> <span class="n">choices</span><span class="o">=</span><span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">4</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;3&#39;</span><span class="p">]))</span>
<span class="go">Namespace(door=3)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;4&#39;</span><span class="p">])</span>
<span class="go">usage: doors.py [-h] {1,2,3}</span>
<span class="go">doors.py: error: argument door: invalid choice: 4 (choose from 1, 2, 3)</span>
</pre></div>
</div>
<p>Any object that supports the <code class="docutils literal notranslate"><span class="pre">in</span></code> operator can be passed as the <em>choices</em>
value, so <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> objects, <a class="reference internal" href="stdtypes.html#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a> objects, custom containers,
etc. are all supported.</p>
</div>
<div class="section" id="required">
<h3>required<a class="headerlink" href="#required" title="永久链接至标题">¶</a></h3>
<p>通常，<a class="reference internal" href="#module-argparse" title="argparse: Command-line option and argument parsing library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">argparse</span></code></a> 模块会认为 <code class="docutils literal notranslate"><span class="pre">-f</span></code> 和 <code class="docutils literal notranslate"><span class="pre">--bar</span></code> 等旗标是指明 <em>可选的</em> 参数，它们总是可以在命令行中被忽略。 要让一个选项成为 <em>必需的</em>，则可以将 <code class="docutils literal notranslate"><span class="pre">True</span></code> 作为 <code class="docutils literal notranslate"><span class="pre">required=</span></code> 关键字参数传给 <a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_argument()</span></code></a>:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">required</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="s1">&#39;BAR&#39;</span><span class="p">])</span>
<span class="go">Namespace(foo=&#39;BAR&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([])</span>
<span class="go">usage: argparse.py [-h] [--foo FOO]</span>
<span class="go">argparse.py: error: option --foo is required</span>
</pre></div>
</div>
<p>如这个例子所示，如果一个选项被标记为 <code class="docutils literal notranslate"><span class="pre">required</span></code>，则当该选项未在命令行中出现时，<a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code></a> 将会报告一个错误。</p>
<div class="admonition note">
<p class="admonition-title">注解</p>
<p>必需的选项通常被认为是不适宜的，因为用户会预期 <em>options</em> 都是 <em>可选的</em>，因此在可能的情况下应当避免使用它们。</p>
</div>
</div>
<div class="section" id="help">
<h3>help<a class="headerlink" href="#help" title="永久链接至标题">¶</a></h3>
<p><code class="docutils literal notranslate"><span class="pre">help</span></code> 值是一个包含参数简短描述的字符串。 当用户请求帮助时（一般是通过在命令行中使用 <code class="docutils literal notranslate"><span class="pre">-h</span></code> 或 <code class="docutils literal notranslate"><span class="pre">--help</span></code> 的方式），这些 <code class="docutils literal notranslate"><span class="pre">help</span></code> 描述将随每个参数一同显示:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;frobble&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;store_true&#39;</span><span class="p">,</span>
<span class="gp">... </span>                    <span class="n">help</span><span class="o">=</span><span class="s1">&#39;foo the bars before frobbling&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;bar&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="s1">&#39;+&#39;</span><span class="p">,</span>
<span class="gp">... </span>                    <span class="n">help</span><span class="o">=</span><span class="s1">&#39;one of the bars to be frobbled&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;-h&#39;</span><span class="p">])</span>
<span class="go">usage: frobble [-h] [--foo] bar [bar ...]</span>

<span class="go">positional arguments:</span>
<span class="go"> bar     one of the bars to be frobbled</span>

<span class="go">optional arguments:</span>
<span class="go"> -h, --help  show this help message and exit</span>
<span class="go"> --foo   foo the bars before frobbling</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">help</span></code> 字符串可包括各种格式描述符以避免重复使用程序名称或参数 <a class="reference internal" href="#default">default</a> 等文本。 有效的描述符包括程序名称 <code class="docutils literal notranslate"><span class="pre">%(prog)s</span></code> 和传给 <a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_argument()</span></code></a> 的大部分关键字参数，例如 <code class="docutils literal notranslate"><span class="pre">%(default)s</span></code>, <code class="docutils literal notranslate"><span class="pre">%(type)s</span></code> 等等:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;frobble&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;bar&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="s1">&#39;?&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="mi">42</span><span class="p">,</span>
<span class="gp">... </span>                    <span class="n">help</span><span class="o">=</span><span class="s1">&#39;the bar to </span><span class="si">%(prog)s</span><span class="s1"> (default: </span><span class="si">%(default)s</span><span class="s1">)&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">print_help</span><span class="p">()</span>
<span class="go">usage: frobble [-h] [bar]</span>

<span class="go">positional arguments:</span>
<span class="go"> bar     the bar to frobble (default: 42)</span>

<span class="go">optional arguments:</span>
<span class="go"> -h, --help  show this help message and exit</span>
</pre></div>
</div>
<p>由于帮助字符串支持 %-formatting，如果你希望在帮助字符串中显示 <code class="docutils literal notranslate"><span class="pre">%</span></code> 字面值，你必须将其转义为 <code class="docutils literal notranslate"><span class="pre">%%</span></code>。</p>
<p><a class="reference internal" href="#module-argparse" title="argparse: Command-line option and argument parsing library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">argparse</span></code></a> 支持静默特定选项的帮助，具体做法是将 <code class="docutils literal notranslate"><span class="pre">help</span></code> 的值设为 <code class="docutils literal notranslate"><span class="pre">argparse.SUPPRESS</span></code>:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;frobble&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="n">argparse</span><span class="o">.</span><span class="n">SUPPRESS</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">print_help</span><span class="p">()</span>
<span class="go">usage: frobble [-h]</span>

<span class="go">optional arguments:</span>
<span class="go">  -h, --help  show this help message and exit</span>
</pre></div>
</div>
</div>
<div class="section" id="metavar">
<h3>metavar<a class="headerlink" href="#metavar" title="永久链接至标题">¶</a></h3>
<p>当 <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> 生成帮助消息时，它需要用某种方式来引用每个预期的参数。 默认情况下，ArgumentParser 对象使用 <a class="reference internal" href="#dest">dest</a> 值作为每个对象的 &quot;name&quot;。 默认情况下，对于位置参数动作，<a class="reference internal" href="#dest">dest</a> 值将被直接使用，而对于可选参数动作，<a class="reference internal" href="#dest">dest</a> 值将被转为大写形式。 因此，一个位置参数 <code class="docutils literal notranslate"><span class="pre">dest='bar'</span></code> 的引用形式将为 <code class="docutils literal notranslate"><span class="pre">bar</span></code>。 一个带有单独命令行参数的可选参数 <code class="docutils literal notranslate"><span class="pre">--foo</span></code> 的引用形式将为 <code class="docutils literal notranslate"><span class="pre">FOO</span></code>。 示例如下:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;bar&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="s1">&#39;X --foo Y&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="go">Namespace(bar=&#39;X&#39;, foo=&#39;Y&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">print_help</span><span class="p">()</span>
<span class="go">usage:  [-h] [--foo FOO] bar</span>

<span class="go">positional arguments:</span>
<span class="go"> bar</span>

<span class="go">optional arguments:</span>
<span class="go"> -h, --help  show this help message and exit</span>
<span class="go"> --foo FOO</span>
</pre></div>
</div>
<p>可以使用 <code class="docutils literal notranslate"><span class="pre">metavar</span></code> 来指定一个替代名称:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">metavar</span><span class="o">=</span><span class="s1">&#39;YYY&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;bar&#39;</span><span class="p">,</span> <span class="n">metavar</span><span class="o">=</span><span class="s1">&#39;XXX&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="s1">&#39;X --foo Y&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="go">Namespace(bar=&#39;X&#39;, foo=&#39;Y&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">print_help</span><span class="p">()</span>
<span class="go">usage:  [-h] [--foo YYY] XXX</span>

<span class="go">positional arguments:</span>
<span class="go"> XXX</span>

<span class="go">optional arguments:</span>
<span class="go"> -h, --help  show this help message and exit</span>
<span class="go"> --foo YYY</span>
</pre></div>
</div>
<p>请注意 <code class="docutils literal notranslate"><span class="pre">metavar</span></code> 仅改变 <em>显示的</em> 名称 -  <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code></a> 对象的属性名称仍然会由 <a class="reference internal" href="#dest">dest</a> 值确定。</p>
<p>不同的 <code class="docutils literal notranslate"><span class="pre">nargs</span></code> 值可能导致 metavar 被多次使用。 提供一个元组给 <code class="docutils literal notranslate"><span class="pre">metavar</span></code> 即为每个参数指定不同的显示信息:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;PROG&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;-x&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="mi">2</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">metavar</span><span class="o">=</span><span class="p">(</span><span class="s1">&#39;bar&#39;</span><span class="p">,</span> <span class="s1">&#39;baz&#39;</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">print_help</span><span class="p">()</span>
<span class="go">usage: PROG [-h] [-x X X] [--foo bar baz]</span>

<span class="go">optional arguments:</span>
<span class="go"> -h, --help     show this help message and exit</span>
<span class="go"> -x X X</span>
<span class="go"> --foo bar baz</span>
</pre></div>
</div>
</div>
<div class="section" id="dest">
<h3>dest<a class="headerlink" href="#dest" title="永久链接至标题">¶</a></h3>
<p>大多数 <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> 动作会添加一些值作为 <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code></a> 所返回对象的一个属性。 该属性的名称由 <a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_argument()</span></code></a> 的 <code class="docutils literal notranslate"><span class="pre">dest</span></code> 关键字参数确定。 对于位置参数动作，<code class="docutils literal notranslate"><span class="pre">dest</span></code> 通常会作为 <a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_argument()</span></code></a> 的第一个参数提供:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;bar&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;XXX&#39;</span><span class="p">])</span>
<span class="go">Namespace(bar=&#39;XXX&#39;)</span>
</pre></div>
</div>
<p>对于可选参数动作，<code class="docutils literal notranslate"><span class="pre">dest</span></code> 的值通常取自选项字符串。 <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> 会通过接受第一个长选项字符串并去掉开头的 <code class="docutils literal notranslate"><span class="pre">--</span></code> 字符串来生成 <code class="docutils literal notranslate"><span class="pre">dest</span></code> 的值。 如果没有提供长选项字符串，则 <code class="docutils literal notranslate"><span class="pre">dest</span></code> 将通过接受第一个短选项字符串并去掉开头的 <code class="docutils literal notranslate"><span class="pre">-</span></code> 字符来获得。 任何内部的 <code class="docutils literal notranslate"><span class="pre">-</span></code> 字符都将被转换为 <code class="docutils literal notranslate"><span class="pre">_</span></code> 字符以确保字符串是有效的属性名称。 下面的例子显示了这种行为:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;-f&#39;</span><span class="p">,</span> <span class="s1">&#39;--foo-bar&#39;</span><span class="p">,</span> <span class="s1">&#39;--foo&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;-x&#39;</span><span class="p">,</span> <span class="s1">&#39;-y&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="s1">&#39;-f 1 -x 2&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="go">Namespace(foo_bar=&#39;1&#39;, x=&#39;2&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="s1">&#39;--foo 1 -y 2&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="go">Namespace(foo_bar=&#39;1&#39;, x=&#39;2&#39;)</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">dest</span></code> 允许提供自定义属性名称:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s1">&#39;bar&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="s1">&#39;--foo XXX&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="go">Namespace(bar=&#39;XXX&#39;)</span>
</pre></div>
</div>
</div>
<div class="section" id="action-classes">
<h3>Action 类<a class="headerlink" href="#action-classes" title="永久链接至标题">¶</a></h3>
<p>Action 类实现了 Action API，它是一个返回可调用对象的可调用对象，返回的可调用对象可处理来自命令行的参数。 任何遵循此 API 的对象均可作为 <code class="docutils literal notranslate"><span class="pre">action</span></code> 形参传给 <code class="xref py py-meth docutils literal notranslate"><span class="pre">add_argument()</span></code>。</p>
<dl class="class">
<dt id="argparse.Action">
<em class="property">class </em><code class="sig-prename descclassname">argparse.</code><code class="sig-name descname">Action</code><span class="sig-paren">(</span><em class="sig-param">option_strings</em>, <em class="sig-param">dest</em>, <em class="sig-param">nargs=None</em>, <em class="sig-param">const=None</em>, <em class="sig-param">default=None</em>, <em class="sig-param">type=None</em>, <em class="sig-param">choices=None</em>, <em class="sig-param">required=False</em>, <em class="sig-param">help=None</em>, <em class="sig-param">metavar=None</em><span class="sig-paren">)</span><a class="headerlink" href="#argparse.Action" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>Action 对象会被 ArgumentParser 用来表示解析从命令行中的一个或多个字符串中解析出单个参数所必须的信息。 Action 类必须接受两个位置参数以及传给 <a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code class="xref py py-meth docutils literal notranslate"><span class="pre">ArgumentParser.add_argument()</span></code></a> 的任何关键字参数，除了 <code class="docutils literal notranslate"><span class="pre">action</span></code> 本身。</p>
<p>Action 的实例（或作为or return value of any callable to the <code class="docutils literal notranslate"><span class="pre">action</span></code> 形参的任何可调用对象的返回值）应当定义 &quot;dest&quot;, &quot;option_strings&quot;, &quot;default&quot;, &quot;type&quot;, &quot;required&quot;, &quot;help&quot; 等属性。 确保这些属性被定义的最容易方式是调用 <code class="docutils literal notranslate"><span class="pre">Action.__init__</span></code>。</p>
<p>Action 的实例应当为可调用对象，因此所有子类都必须重载 <code class="docutils literal notranslate"><span class="pre">__call__</span></code> 方法，该方法应当接受四个形参:</p>
<ul class="simple">
<li><p><code class="docutils literal notranslate"><span class="pre">parser</span></code> - 包含此动作的 ArgumentParser 对象。</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">namespace</span></code> - 将由 <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code></a> 返回的 <a class="reference internal" href="#argparse.Namespace" title="argparse.Namespace"><code class="xref py py-class docutils literal notranslate"><span class="pre">Namespace</span></code></a> 对象。 大多数动作会使用 <a class="reference internal" href="functions.html#setattr" title="setattr"><code class="xref py py-func docutils literal notranslate"><span class="pre">setattr()</span></code></a> 为此对象添加属性。</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">values</span></code> - 已关联的命令行参数，并提供相应的类型转换。 类型转换由 <a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_argument()</span></code></a> 的 <a class="reference internal" href="#type">type</a> 关键字参数来指定。</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">option_string</span></code> - 被用来发起调用此动作的选项字符串。 <code class="docutils literal notranslate"><span class="pre">option_string</span></code> 参数是可选的，且此参数在动作关联到位置参数时将被略去。</p></li>
</ul>
<p><code class="docutils literal notranslate"><span class="pre">__call__</span></code> 方法可以执行任意动作，但通常将基于 <code class="docutils literal notranslate"><span class="pre">dest</span></code> 和 <code class="docutils literal notranslate"><span class="pre">values</span></code> 来设置 <code class="docutils literal notranslate"><span class="pre">namespace</span></code> 的属性。</p>
</div>
</div>
<div class="section" id="the-parse-args-method">
<h2>parse_args() 方法<a class="headerlink" href="#the-parse-args-method" title="永久链接至标题">¶</a></h2>
<dl class="method">
<dt id="argparse.ArgumentParser.parse_args">
<code class="sig-prename descclassname">ArgumentParser.</code><code class="sig-name descname">parse_args</code><span class="sig-paren">(</span><em class="sig-param">args=None</em>, <em class="sig-param">namespace=None</em><span class="sig-paren">)</span><a class="headerlink" href="#argparse.ArgumentParser.parse_args" title="永久链接至目标">¶</a></dt>
<dd><p>将参数字符串转换为对象并将其设为命名空间的属性。 返回带有成员的命名空间。</p>
<p>之前对 <a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_argument()</span></code></a> 的调用决定了哪些对象被创建以及它们如何被赋值。 请参阅 <a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_argument()</span></code></a> 的文档了解详情。</p>
<ul class="simple">
<li><p><a class="reference internal" href="#args">args</a> - 要解析的字符串列表。 默认情况下是从 <a class="reference internal" href="sys.html#sys.argv" title="sys.argv"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.argv</span></code></a> 获取。</p></li>
<li><p><a class="reference internal" href="#namespace">namespace</a> - 用于获取属性的对象。 默认值是一个新的空 <a class="reference internal" href="#argparse.Namespace" title="argparse.Namespace"><code class="xref py py-class docutils literal notranslate"><span class="pre">Namespace</span></code></a> 对象。</p></li>
</ul>
</dd></dl>

<div class="section" id="option-value-syntax">
<h3>选项值语法<a class="headerlink" href="#option-value-syntax" title="永久链接至标题">¶</a></h3>
<p><a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code></a> 方法支持多种指定选项值的方式（如果它接受选项的话）。 在最简单的情况下，选项和它的值是作为两个单独参数传入的:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;PROG&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;-x&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;-x&#39;</span><span class="p">,</span> <span class="s1">&#39;X&#39;</span><span class="p">])</span>
<span class="go">Namespace(foo=None, x=&#39;X&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="s1">&#39;FOO&#39;</span><span class="p">])</span>
<span class="go">Namespace(foo=&#39;FOO&#39;, x=None)</span>
</pre></div>
</div>
<p>对于长选项（名称长度超过一个字符的选项），选项和值也可以作为单个命令行参数传入，使用 <code class="docutils literal notranslate"><span class="pre">=</span></code> 分隔它们即可:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;--foo=FOO&#39;</span><span class="p">])</span>
<span class="go">Namespace(foo=&#39;FOO&#39;, x=None)</span>
</pre></div>
</div>
<p>对于短选项（长度只有一个字符的选项），选项和它的值可以拼接在一起:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;-xX&#39;</span><span class="p">])</span>
<span class="go">Namespace(foo=None, x=&#39;X&#39;)</span>
</pre></div>
</div>
<p>有些短选项可以使用单个 <code class="docutils literal notranslate"><span class="pre">-</span></code> 前缀来进行合并，如果仅有最后一个选项（或没有任何选项）需要值的话:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;PROG&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;-x&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;store_true&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;-y&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;store_true&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;-z&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;-xyzZ&#39;</span><span class="p">])</span>
<span class="go">Namespace(x=True, y=True, z=&#39;Z&#39;)</span>
</pre></div>
</div>
</div>
<div class="section" id="invalid-arguments">
<h3>无效的参数<a class="headerlink" href="#invalid-arguments" title="永久链接至标题">¶</a></h3>
<p>在解析命令行时，<a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code></a> 会检测多种错误，包括有歧义的选项、无效的类型、无效的选项、错误的位置参数个数等等。 当遇到这种错误时，它将退出并打印出错误文本同时附带用法消息:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;PROG&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;bar&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="s1">&#39;?&#39;</span><span class="p">)</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># invalid type</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="s1">&#39;spam&#39;</span><span class="p">])</span>
<span class="go">usage: PROG [-h] [--foo FOO] [bar]</span>
<span class="go">PROG: error: argument --foo: invalid int value: &#39;spam&#39;</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># invalid option</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;--bar&#39;</span><span class="p">])</span>
<span class="go">usage: PROG [-h] [--foo FOO] [bar]</span>
<span class="go">PROG: error: no such option: --bar</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># wrong number of arguments</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;spam&#39;</span><span class="p">,</span> <span class="s1">&#39;badger&#39;</span><span class="p">])</span>
<span class="go">usage: PROG [-h] [--foo FOO] [bar]</span>
<span class="go">PROG: error: extra arguments found: badger</span>
</pre></div>
</div>
</div>
<div class="section" id="arguments-containing">
<h3>包含 <code class="docutils literal notranslate"><span class="pre">-</span></code> 的参数<a class="headerlink" href="#arguments-containing" title="永久链接至标题">¶</a></h3>
<p><a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code></a> 方法会在用户明显出错时尝试给出错误信息，但某些情况本身就存在歧义。 例如，命令行参数 <code class="docutils literal notranslate"><span class="pre">-1</span></code> 可能是尝试指定一个选项也可能是尝试提供一个位置参数。 <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code></a> 方法在此会谨慎行事：位置参数只有在它们看起来像负数并且解析器中没有任何选项看起来像负数时才能以 <code class="docutils literal notranslate"><span class="pre">-</span></code> 打头。:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;PROG&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;-x&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;foo&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="s1">&#39;?&#39;</span><span class="p">)</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># no negative number options, so -1 is a positional argument</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;-x&#39;</span><span class="p">,</span> <span class="s1">&#39;-1&#39;</span><span class="p">])</span>
<span class="go">Namespace(foo=None, x=&#39;-1&#39;)</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># no negative number options, so -1 and -5 are positional arguments</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;-x&#39;</span><span class="p">,</span> <span class="s1">&#39;-1&#39;</span><span class="p">,</span> <span class="s1">&#39;-5&#39;</span><span class="p">])</span>
<span class="go">Namespace(foo=&#39;-5&#39;, x=&#39;-1&#39;)</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;PROG&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;-1&#39;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s1">&#39;one&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;foo&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="s1">&#39;?&#39;</span><span class="p">)</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># negative number options present, so -1 is an option</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;-1&#39;</span><span class="p">,</span> <span class="s1">&#39;X&#39;</span><span class="p">])</span>
<span class="go">Namespace(foo=None, one=&#39;X&#39;)</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># negative number options present, so -2 is an option</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;-2&#39;</span><span class="p">])</span>
<span class="go">usage: PROG [-h] [-1 ONE] [foo]</span>
<span class="go">PROG: error: no such option: -2</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># negative number options present, so both -1s are options</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;-1&#39;</span><span class="p">,</span> <span class="s1">&#39;-1&#39;</span><span class="p">])</span>
<span class="go">usage: PROG [-h] [-1 ONE] [foo]</span>
<span class="go">PROG: error: argument -1: expected one argument</span>
</pre></div>
</div>
<p>如果你有必须以 <code class="docutils literal notranslate"><span class="pre">-</span></code> 打头的位置参数并且看起来不像负数，你可以插入伪参数 <code class="docutils literal notranslate"><span class="pre">'--'</span></code> 以告诉 <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code></a> 在那之后的内容是一个位置参数:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;--&#39;</span><span class="p">,</span> <span class="s1">&#39;-f&#39;</span><span class="p">])</span>
<span class="go">Namespace(foo=&#39;-f&#39;, one=None)</span>
</pre></div>
</div>
</div>
<div class="section" id="argument-abbreviations-prefix-matching">
<span id="prefix-matching"></span><h3>参数缩写（前缀匹配）<a class="headerlink" href="#argument-abbreviations-prefix-matching" title="永久链接至标题">¶</a></h3>
<p><a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code></a> 方法 <a class="reference internal" href="#allow-abbrev"><span class="std std-ref">在默认情况下</span></a> 允许将长选项缩写为前缀，如果缩写无歧义（即前缀与一个特定选项相匹配）的话:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;PROG&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;-bacon&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;-badger&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="s1">&#39;-bac MMM&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="go">Namespace(bacon=&#39;MMM&#39;, badger=None)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="s1">&#39;-bad WOOD&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="go">Namespace(bacon=None, badger=&#39;WOOD&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="s1">&#39;-ba BA&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="go">usage: PROG [-h] [-bacon BACON] [-badger BADGER]</span>
<span class="go">PROG: error: ambiguous option: -ba could match -badger, -bacon</span>
</pre></div>
</div>
<p>可产生一个以上选项的参数会引发错误。 此特定可通过将 <a class="reference internal" href="#allow-abbrev"><span class="std std-ref">allow_abbrev</span></a> 设为 <code class="docutils literal notranslate"><span class="pre">False</span></code> 来禁用。</p>
</div>
<div class="section" id="beyond-sys-argv">
<span id="args"></span><h3>在 <code class="docutils literal notranslate"><span class="pre">sys.argv</span></code> 以外<a class="headerlink" href="#beyond-sys-argv" title="永久链接至标题">¶</a></h3>
<p>有时在 <a class="reference internal" href="sys.html#sys.argv" title="sys.argv"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.argv</span></code></a> 以外用 ArgumentParser 解析参数也是有用的。 这可以通过将一个字符串列表传给 <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code></a> 来实现。 它适用于在交互提示符下进行检测:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span>
<span class="gp">... </span>    <span class="s1">&#39;integers&#39;</span><span class="p">,</span> <span class="n">metavar</span><span class="o">=</span><span class="s1">&#39;int&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">,</span> <span class="n">choices</span><span class="o">=</span><span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">),</span>
<span class="gp">... </span>    <span class="n">nargs</span><span class="o">=</span><span class="s1">&#39;+&#39;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s1">&#39;an integer in the range 0..9&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span>
<span class="gp">... </span>    <span class="s1">&#39;--sum&#39;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s1">&#39;accumulate&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;store_const&#39;</span><span class="p">,</span> <span class="n">const</span><span class="o">=</span><span class="nb">sum</span><span class="p">,</span>
<span class="gp">... </span>    <span class="n">default</span><span class="o">=</span><span class="nb">max</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s1">&#39;sum the integers (default: find the max)&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;1&#39;</span><span class="p">,</span> <span class="s1">&#39;2&#39;</span><span class="p">,</span> <span class="s1">&#39;3&#39;</span><span class="p">,</span> <span class="s1">&#39;4&#39;</span><span class="p">])</span>
<span class="go">Namespace(accumulate=&lt;built-in function max&gt;, integers=[1, 2, 3, 4])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;1&#39;</span><span class="p">,</span> <span class="s1">&#39;2&#39;</span><span class="p">,</span> <span class="s1">&#39;3&#39;</span><span class="p">,</span> <span class="s1">&#39;4&#39;</span><span class="p">,</span> <span class="s1">&#39;--sum&#39;</span><span class="p">])</span>
<span class="go">Namespace(accumulate=&lt;built-in function sum&gt;, integers=[1, 2, 3, 4])</span>
</pre></div>
</div>
</div>
<div class="section" id="the-namespace-object">
<span id="namespace"></span><h3>命名空间对象<a class="headerlink" href="#the-namespace-object" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="argparse.Namespace">
<em class="property">class </em><code class="sig-prename descclassname">argparse.</code><code class="sig-name descname">Namespace</code><a class="headerlink" href="#argparse.Namespace" title="永久链接至目标">¶</a></dt>
<dd><p>由 <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code></a> 默认使用的简单类，可创建一个存放属性的对象并将其返回。</p>
</dd></dl>

<p>这个类被有意做得很简单，只是一个具有可读字符串表示形式的 <a class="reference internal" href="functions.html#object" title="object"><code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></a>。 如果你更喜欢类似字典的属性视图，你可以使用标准 Python 中惯常的 <a class="reference internal" href="functions.html#vars" title="vars"><code class="xref py py-func docutils literal notranslate"><span class="pre">vars()</span></code></a>:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">args</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="s1">&#39;BAR&#39;</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">vars</span><span class="p">(</span><span class="n">args</span><span class="p">)</span>
<span class="go">{&#39;foo&#39;: &#39;BAR&#39;}</span>
</pre></div>
</div>
<p>另一个用处是让 <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> 为一个已存在对象而不是为一个新的 <a class="reference internal" href="#argparse.Namespace" title="argparse.Namespace"><code class="xref py py-class docutils literal notranslate"><span class="pre">Namespace</span></code></a> 对象的属性赋值。 这可以通过指定 <code class="docutils literal notranslate"><span class="pre">namespace=</span></code> 关键字参数来实现:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">C</span><span class="p">:</span>
<span class="gp">... </span>    <span class="k">pass</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">C</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="n">args</span><span class="o">=</span><span class="p">[</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="s1">&#39;BAR&#39;</span><span class="p">],</span> <span class="n">namespace</span><span class="o">=</span><span class="n">c</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="o">.</span><span class="n">foo</span>
<span class="go">&#39;BAR&#39;</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="other-utilities">
<h2>其它实用工具<a class="headerlink" href="#other-utilities" title="永久链接至标题">¶</a></h2>
<div class="section" id="sub-commands">
<h3>子命令<a class="headerlink" href="#sub-commands" title="永久链接至标题">¶</a></h3>
<dl class="method">
<dt id="argparse.ArgumentParser.add_subparsers">
<code class="sig-prename descclassname">ArgumentParser.</code><code class="sig-name descname">add_subparsers</code><span class="sig-paren">(</span><span class="optional">[</span><em class="sig-param">title</em><span class="optional">]</span><span class="optional">[</span>, <em class="sig-param">description</em><span class="optional">]</span><span class="optional">[</span>, <em class="sig-param">prog</em><span class="optional">]</span><span class="optional">[</span>, <em class="sig-param">parser_class</em><span class="optional">]</span><span class="optional">[</span>, <em class="sig-param">action</em><span class="optional">]</span><span class="optional">[</span>, <em class="sig-param">option_string</em><span class="optional">]</span><span class="optional">[</span>, <em class="sig-param">dest</em><span class="optional">]</span><span class="optional">[</span>, <em class="sig-param">required</em><span class="optional">]</span><span class="optional">[</span>, <em class="sig-param">help</em><span class="optional">]</span><span class="optional">[</span>, <em class="sig-param">metavar</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#argparse.ArgumentParser.add_subparsers" title="永久链接至目标">¶</a></dt>
<dd><p>许多程序都会将其功能拆分为一系列子命令，例如，<code class="docutils literal notranslate"><span class="pre">svn</span></code> 程序包含的子命令有 <code class="docutils literal notranslate"><span class="pre">svn</span> <span class="pre">checkout</span></code>, <code class="docutils literal notranslate"><span class="pre">svn</span> <span class="pre">update</span></code> 和 <code class="docutils literal notranslate"><span class="pre">svn</span> <span class="pre">commit</span></code>。 当一个程序能执行需要多组不同种类命令行参数时这种拆分功能的方式是一个非常好的主意。 <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> 通过 <a class="reference internal" href="#argparse.ArgumentParser.add_subparsers" title="argparse.ArgumentParser.add_subparsers"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_subparsers()</span></code></a> 方法支持创建这样的子命令。 <a class="reference internal" href="#argparse.ArgumentParser.add_subparsers" title="argparse.ArgumentParser.add_subparsers"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_subparsers()</span></code></a> 方法通常不带参数地调用并返回一个特殊的动作对象。 这种对象只有一个方法 <code class="xref py py-meth docutils literal notranslate"><span class="pre">add_parser()</span></code>，它接受一个命令名称和任意多个 <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> 构造器参数，并返回一个可以通常方式进行修改的 <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> 对象。</p>
<p>形参的描述</p>
<ul class="simple">
<li><p>title - 输出帮助的子解析器分组的标题；如果提供了描述则默认为 &quot;subcommands&quot;，否则使用位置参数的标题</p></li>
<li><p>description - 输出帮助中对子解析器的描述，默认为 <code class="docutils literal notranslate"><span class="pre">None</span></code></p></li>
<li><p>prog - 将与子命令帮助一同显示的用法信息，默认为程序名称和子解析器参数之前的任何位置参数。</p></li>
<li><p>parser_class - 将被用于创建子解析器实例的类，默认为当前解析器类（例如 ArgumentParser）</p></li>
<li><p><a class="reference internal" href="#action">action</a> - 当此参数在命令行中出现时要执行动作的基本类型</p></li>
<li><p><a class="reference internal" href="#dest">dest</a> - 将被用于保存子命令名称的属性名；默认为 <code class="docutils literal notranslate"><span class="pre">None</span></code> 即不保存任何值</p></li>
<li><p><a class="reference internal" href="#required">required</a> - 是否必须要提供子命令，默认为 <code class="docutils literal notranslate"><span class="pre">False</span></code> (在 3.7 中新增)</p></li>
<li><p><a class="reference internal" href="#help">help</a> - 在输出帮助中的子解析器分组帮助信息，默认为 <code class="docutils literal notranslate"><span class="pre">None</span></code></p></li>
<li><p><a class="reference internal" href="#metavar">metavar</a> - 帮助信息中表示可用子命令的字符串；默认为 <code class="docutils literal notranslate"><span class="pre">None</span></code> 并以 {cmd1, cmd2, ..} 的形式表示子命令</p></li>
</ul>
<p>一些使用示例:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="c1"># create the top-level parser</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;PROG&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;store_true&#39;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s1">&#39;foo help&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">subparsers</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">add_subparsers</span><span class="p">(</span><span class="n">help</span><span class="o">=</span><span class="s1">&#39;sub-command help&#39;</span><span class="p">)</span>
<span class="go">&gt;&gt;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># create the parser for the &quot;a&quot; command</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser_a</span> <span class="o">=</span> <span class="n">subparsers</span><span class="o">.</span><span class="n">add_parser</span><span class="p">(</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s1">&#39;a help&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser_a</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;bar&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s1">&#39;bar help&#39;</span><span class="p">)</span>
<span class="go">&gt;&gt;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># create the parser for the &quot;b&quot; command</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser_b</span> <span class="o">=</span> <span class="n">subparsers</span><span class="o">.</span><span class="n">add_parser</span><span class="p">(</span><span class="s1">&#39;b&#39;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s1">&#39;b help&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser_b</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--baz&#39;</span><span class="p">,</span> <span class="n">choices</span><span class="o">=</span><span class="s1">&#39;XYZ&#39;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s1">&#39;baz help&#39;</span><span class="p">)</span>
<span class="go">&gt;&gt;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># parse some argument lists</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="s1">&#39;12&#39;</span><span class="p">])</span>
<span class="go">Namespace(bar=12, foo=False)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="s1">&#39;b&#39;</span><span class="p">,</span> <span class="s1">&#39;--baz&#39;</span><span class="p">,</span> <span class="s1">&#39;Z&#39;</span><span class="p">])</span>
<span class="go">Namespace(baz=&#39;Z&#39;, foo=True)</span>
</pre></div>
</div>
<p>请注意 <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code></a> 返回的对象将只包含主解析器和由命令行所选择的子解析器的属性（而没有任何其他子解析器）。 因此在上面的例子中，当指定了 <code class="docutils literal notranslate"><span class="pre">a</span></code> 命令时，将只存在 <code class="docutils literal notranslate"><span class="pre">foo</span></code> 和 <code class="docutils literal notranslate"><span class="pre">bar</span></code> 属性，而当指定了 <code class="docutils literal notranslate"><span class="pre">b</span></code> 命令时，则只存在 <code class="docutils literal notranslate"><span class="pre">foo</span></code> 和 <code class="docutils literal notranslate"><span class="pre">baz</span></code> 属性。</p>
<p>类似地，当从一个子解析器请求帮助消息时，只有该特定解析器的帮助消息会被打印出来。 帮助消息将不包括父解析器或同级解析器的消息。 （每个子解析器命令一条帮助消息，但是，也可以像上面那样通过提供 <code class="docutils literal notranslate"><span class="pre">help=</span></code> 参数给 <code class="xref py py-meth docutils literal notranslate"><span class="pre">add_parser()</span></code> 来给出。）</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;--help&#39;</span><span class="p">])</span>
<span class="go">usage: PROG [-h] [--foo] {a,b} ...</span>

<span class="go">positional arguments:</span>
<span class="go">  {a,b}   sub-command help</span>
<span class="go">    a     a help</span>
<span class="go">    b     b help</span>

<span class="go">optional arguments:</span>
<span class="go">  -h, --help  show this help message and exit</span>
<span class="go">  --foo   foo help</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="s1">&#39;--help&#39;</span><span class="p">])</span>
<span class="go">usage: PROG a [-h] bar</span>

<span class="go">positional arguments:</span>
<span class="go">  bar     bar help</span>

<span class="go">optional arguments:</span>
<span class="go">  -h, --help  show this help message and exit</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;b&#39;</span><span class="p">,</span> <span class="s1">&#39;--help&#39;</span><span class="p">])</span>
<span class="go">usage: PROG b [-h] [--baz {X,Y,Z}]</span>

<span class="go">optional arguments:</span>
<span class="go">  -h, --help     show this help message and exit</span>
<span class="go">  --baz {X,Y,Z}  baz help</span>
</pre></div>
</div>
<p><a class="reference internal" href="#argparse.ArgumentParser.add_subparsers" title="argparse.ArgumentParser.add_subparsers"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_subparsers()</span></code></a> 方法也支持 <code class="docutils literal notranslate"><span class="pre">title</span></code> 和 <code class="docutils literal notranslate"><span class="pre">description</span></code> 关键字参数。 当两者都存在时，子解析器的命令将出现在输出帮助消息中它们自己的分组内。 例如:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">subparsers</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">add_subparsers</span><span class="p">(</span><span class="n">title</span><span class="o">=</span><span class="s1">&#39;subcommands&#39;</span><span class="p">,</span>
<span class="gp">... </span>                                   <span class="n">description</span><span class="o">=</span><span class="s1">&#39;valid subcommands&#39;</span><span class="p">,</span>
<span class="gp">... </span>                                   <span class="n">help</span><span class="o">=</span><span class="s1">&#39;additional help&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">subparsers</span><span class="o">.</span><span class="n">add_parser</span><span class="p">(</span><span class="s1">&#39;foo&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">subparsers</span><span class="o">.</span><span class="n">add_parser</span><span class="p">(</span><span class="s1">&#39;bar&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;-h&#39;</span><span class="p">])</span>
<span class="go">usage:  [-h] {foo,bar} ...</span>

<span class="go">optional arguments:</span>
<span class="go">  -h, --help  show this help message and exit</span>

<span class="go">subcommands:</span>
<span class="go">  valid subcommands</span>

<span class="go">  {foo,bar}   additional help</span>
</pre></div>
</div>
<p>此外，<code class="docutils literal notranslate"><span class="pre">add_parser</span></code> 还支持附加的 <code class="docutils literal notranslate"><span class="pre">aliases</span></code> 参数，它允许多个字符串指向同一子解析器。 这个例子类似于 <code class="docutils literal notranslate"><span class="pre">svn</span></code>，将别名 <code class="docutils literal notranslate"><span class="pre">co</span></code> 设为 <code class="docutils literal notranslate"><span class="pre">checkout</span></code> 的缩写形式:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">subparsers</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">add_subparsers</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">checkout</span> <span class="o">=</span> <span class="n">subparsers</span><span class="o">.</span><span class="n">add_parser</span><span class="p">(</span><span class="s1">&#39;checkout&#39;</span><span class="p">,</span> <span class="n">aliases</span><span class="o">=</span><span class="p">[</span><span class="s1">&#39;co&#39;</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">checkout</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;foo&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;co&#39;</span><span class="p">,</span> <span class="s1">&#39;bar&#39;</span><span class="p">])</span>
<span class="go">Namespace(foo=&#39;bar&#39;)</span>
</pre></div>
</div>
<p>一个特别有效的处理子命令的方式是将 <a class="reference internal" href="#argparse.ArgumentParser.add_subparsers" title="argparse.ArgumentParser.add_subparsers"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_subparsers()</span></code></a> 方法与对 <a class="reference internal" href="#argparse.ArgumentParser.set_defaults" title="argparse.ArgumentParser.set_defaults"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set_defaults()</span></code></a> 的调用结合起来使用，这样每个子解析器就能知道应当执行哪个 Python 函数。 例如:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="c1"># sub-command functions</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">foo</span><span class="p">(</span><span class="n">args</span><span class="p">):</span>
<span class="gp">... </span>    <span class="nb">print</span><span class="p">(</span><span class="n">args</span><span class="o">.</span><span class="n">x</span> <span class="o">*</span> <span class="n">args</span><span class="o">.</span><span class="n">y</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">bar</span><span class="p">(</span><span class="n">args</span><span class="p">):</span>
<span class="gp">... </span>    <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;((</span><span class="si">%s</span><span class="s1">))&#39;</span> <span class="o">%</span> <span class="n">args</span><span class="o">.</span><span class="n">z</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># create the top-level parser</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">subparsers</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">add_subparsers</span><span class="p">()</span>
<span class="go">&gt;&gt;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># create the parser for the &quot;foo&quot; command</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser_foo</span> <span class="o">=</span> <span class="n">subparsers</span><span class="o">.</span><span class="n">add_parser</span><span class="p">(</span><span class="s1">&#39;foo&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser_foo</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;-x&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser_foo</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;y&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">float</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser_foo</span><span class="o">.</span><span class="n">set_defaults</span><span class="p">(</span><span class="n">func</span><span class="o">=</span><span class="n">foo</span><span class="p">)</span>
<span class="go">&gt;&gt;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># create the parser for the &quot;bar&quot; command</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser_bar</span> <span class="o">=</span> <span class="n">subparsers</span><span class="o">.</span><span class="n">add_parser</span><span class="p">(</span><span class="s1">&#39;bar&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser_bar</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;z&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser_bar</span><span class="o">.</span><span class="n">set_defaults</span><span class="p">(</span><span class="n">func</span><span class="o">=</span><span class="n">bar</span><span class="p">)</span>
<span class="go">&gt;&gt;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># parse the args and call whatever function was selected</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">args</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="s1">&#39;foo 1 -x 2&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">args</span><span class="o">.</span><span class="n">func</span><span class="p">(</span><span class="n">args</span><span class="p">)</span>
<span class="go">2.0</span>
<span class="go">&gt;&gt;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># parse the args and call whatever function was selected</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">args</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="s1">&#39;bar XYZYX&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">args</span><span class="o">.</span><span class="n">func</span><span class="p">(</span><span class="n">args</span><span class="p">)</span>
<span class="go">((XYZYX))</span>
</pre></div>
</div>
<p>通过这种方式，你可以在参数解析结束后让 <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code></a> 执行调用适当函数的任务。 像这样将函数关联到动作通常是你处理每个子解析器的不同动作的最简便方式。 但是，如果有必要检查被发起调用的子解析器的名称，则 <a class="reference internal" href="#argparse.ArgumentParser.add_subparsers" title="argparse.ArgumentParser.add_subparsers"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_subparsers()</span></code></a> 调用的 <code class="docutils literal notranslate"><span class="pre">dest</span></code> 关键字参数将可实现:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">subparsers</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">add_subparsers</span><span class="p">(</span><span class="n">dest</span><span class="o">=</span><span class="s1">&#39;subparser_name&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">subparser1</span> <span class="o">=</span> <span class="n">subparsers</span><span class="o">.</span><span class="n">add_parser</span><span class="p">(</span><span class="s1">&#39;1&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">subparser1</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;-x&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">subparser2</span> <span class="o">=</span> <span class="n">subparsers</span><span class="o">.</span><span class="n">add_parser</span><span class="p">(</span><span class="s1">&#39;2&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">subparser2</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;y&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;2&#39;</span><span class="p">,</span> <span class="s1">&#39;frobble&#39;</span><span class="p">])</span>
<span class="go">Namespace(subparser_name=&#39;2&#39;, y=&#39;frobble&#39;)</span>
</pre></div>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.7 版更改: </span>新增 <em>required</em> 关键字参数。</p>
</div>
</dd></dl>

</div>
<div class="section" id="filetype-objects">
<h3>FileType 对象<a class="headerlink" href="#filetype-objects" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="argparse.FileType">
<em class="property">class </em><code class="sig-prename descclassname">argparse.</code><code class="sig-name descname">FileType</code><span class="sig-paren">(</span><em class="sig-param">mode='r'</em>, <em class="sig-param">bufsize=-1</em>, <em class="sig-param">encoding=None</em>, <em class="sig-param">errors=None</em><span class="sig-paren">)</span><a class="headerlink" href="#argparse.FileType" title="永久链接至目标">¶</a></dt>
<dd><p><a class="reference internal" href="#argparse.FileType" title="argparse.FileType"><code class="xref py py-class docutils literal notranslate"><span class="pre">FileType</span></code></a> 工厂类用于创建可作为 <a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code class="xref py py-meth docutils literal notranslate"><span class="pre">ArgumentParser.add_argument()</span></code></a> 的 type 参数传入的对象。 以 <a class="reference internal" href="#argparse.FileType" title="argparse.FileType"><code class="xref py py-class docutils literal notranslate"><span class="pre">FileType</span></code></a> 对象作为其类型的参数将使用命令行参数以所请求模式、缓冲区大小、编码格式和错误处理方式打开文件（请参阅 <a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> 函数了解详情）:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--raw&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="n">argparse</span><span class="o">.</span><span class="n">FileType</span><span class="p">(</span><span class="s1">&#39;wb&#39;</span><span class="p">,</span> <span class="mi">0</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;out&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="n">argparse</span><span class="o">.</span><span class="n">FileType</span><span class="p">(</span><span class="s1">&#39;w&#39;</span><span class="p">,</span> <span class="n">encoding</span><span class="o">=</span><span class="s1">&#39;UTF-8&#39;</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;--raw&#39;</span><span class="p">,</span> <span class="s1">&#39;raw.dat&#39;</span><span class="p">,</span> <span class="s1">&#39;file.txt&#39;</span><span class="p">])</span>
<span class="go">Namespace(out=&lt;_io.TextIOWrapper name=&#39;file.txt&#39; mode=&#39;w&#39; encoding=&#39;UTF-8&#39;&gt;, raw=&lt;_io.FileIO name=&#39;raw.dat&#39; mode=&#39;wb&#39;&gt;)</span>
</pre></div>
</div>
<p>FileType 对象能理解伪参数 <code class="docutils literal notranslate"><span class="pre">'-'</span></code> 并会自动将其转换为 <code class="docutils literal notranslate"><span class="pre">sys.stdin</span></code> 用于可读的 <a class="reference internal" href="#argparse.FileType" title="argparse.FileType"><code class="xref py py-class docutils literal notranslate"><span class="pre">FileType</span></code></a> 对象，或是 <code class="docutils literal notranslate"><span class="pre">sys.stdout</span></code> 用于可写的 <a class="reference internal" href="#argparse.FileType" title="argparse.FileType"><code class="xref py py-class docutils literal notranslate"><span class="pre">FileType</span></code></a> 对象:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;infile&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="n">argparse</span><span class="o">.</span><span class="n">FileType</span><span class="p">(</span><span class="s1">&#39;r&#39;</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;-&#39;</span><span class="p">])</span>
<span class="go">Namespace(infile=&lt;_io.TextIOWrapper name=&#39;&lt;stdin&gt;&#39; encoding=&#39;UTF-8&#39;&gt;)</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified added">3.4 新版功能: </span><em>encodings</em> 和 <em>errors</em> 关键字参数。</p>
</div>
</dd></dl>

</div>
<div class="section" id="argument-groups">
<h3>参数组<a class="headerlink" href="#argument-groups" title="永久链接至标题">¶</a></h3>
<dl class="method">
<dt id="argparse.ArgumentParser.add_argument_group">
<code class="sig-prename descclassname">ArgumentParser.</code><code class="sig-name descname">add_argument_group</code><span class="sig-paren">(</span><em class="sig-param">title=None</em>, <em class="sig-param">description=None</em><span class="sig-paren">)</span><a class="headerlink" href="#argparse.ArgumentParser.add_argument_group" title="永久链接至目标">¶</a></dt>
<dd><p>在默认情况下，<a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> 会在显示帮助消息时将命令行参数分为“位置参数”和“可选参数”两组。 当存在比默认更好的参数分组概念时，可以使用 <a class="reference internal" href="#argparse.ArgumentParser.add_argument_group" title="argparse.ArgumentParser.add_argument_group"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_argument_group()</span></code></a> 方法来创建适当的分组:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;PROG&#39;</span><span class="p">,</span> <span class="n">add_help</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">group</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">add_argument_group</span><span class="p">(</span><span class="s1">&#39;group&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">group</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s1">&#39;foo help&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">group</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;bar&#39;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s1">&#39;bar help&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">print_help</span><span class="p">()</span>
<span class="go">usage: PROG [--foo FOO] bar</span>

<span class="go">group:</span>
<span class="go">  bar    bar help</span>
<span class="go">  --foo FOO  foo help</span>
</pre></div>
</div>
<p><a class="reference internal" href="#argparse.ArgumentParser.add_argument_group" title="argparse.ArgumentParser.add_argument_group"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_argument_group()</span></code></a> 方法返回一个具有 <a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_argument()</span></code></a> 方法的参数分组对象，这与常规的 <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> 一样。 当一个参数被加入分组时，解析器会将它视为一个正常的参数，但是会在不同的帮助消息分组中显示该参数。 <a class="reference internal" href="#argparse.ArgumentParser.add_argument_group" title="argparse.ArgumentParser.add_argument_group"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_argument_group()</span></code></a> 方法接受 <em>title</em> 和 <em>description</em> 参数，它们可被用来定制显示内容:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;PROG&#39;</span><span class="p">,</span> <span class="n">add_help</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">group1</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">add_argument_group</span><span class="p">(</span><span class="s1">&#39;group1&#39;</span><span class="p">,</span> <span class="s1">&#39;group1 description&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">group1</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;foo&#39;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s1">&#39;foo help&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">group2</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">add_argument_group</span><span class="p">(</span><span class="s1">&#39;group2&#39;</span><span class="p">,</span> <span class="s1">&#39;group2 description&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">group2</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--bar&#39;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s1">&#39;bar help&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">print_help</span><span class="p">()</span>
<span class="go">usage: PROG [--bar BAR] foo</span>

<span class="go">group1:</span>
<span class="go">  group1 description</span>

<span class="go">  foo    foo help</span>

<span class="go">group2:</span>
<span class="go">  group2 description</span>

<span class="go">  --bar BAR  bar help</span>
</pre></div>
</div>
<p>请注意任意不在你的自定义分组中的参数最终都将回到通常的“位置参数”和“可选参数”分组中。</p>
</dd></dl>

</div>
<div class="section" id="mutual-exclusion">
<h3>互斥<a class="headerlink" href="#mutual-exclusion" title="永久链接至标题">¶</a></h3>
<dl class="method">
<dt id="argparse.ArgumentParser.add_mutually_exclusive_group">
<code class="sig-prename descclassname">ArgumentParser.</code><code class="sig-name descname">add_mutually_exclusive_group</code><span class="sig-paren">(</span><em class="sig-param">required=False</em><span class="sig-paren">)</span><a class="headerlink" href="#argparse.ArgumentParser.add_mutually_exclusive_group" title="永久链接至目标">¶</a></dt>
<dd><p>创建一个互斥组。 <a class="reference internal" href="#module-argparse" title="argparse: Command-line option and argument parsing library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">argparse</span></code></a> 将会确保互斥组中只有一个参数在命令行中可用:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;PROG&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">group</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">add_mutually_exclusive_group</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">group</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;store_true&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">group</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--bar&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;store_false&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;--foo&#39;</span><span class="p">])</span>
<span class="go">Namespace(bar=True, foo=True)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;--bar&#39;</span><span class="p">])</span>
<span class="go">Namespace(bar=False, foo=False)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="s1">&#39;--bar&#39;</span><span class="p">])</span>
<span class="go">usage: PROG [-h] [--foo | --bar]</span>
<span class="go">PROG: error: argument --bar: not allowed with argument --foo</span>
</pre></div>
</div>
<p><a class="reference internal" href="#argparse.ArgumentParser.add_mutually_exclusive_group" title="argparse.ArgumentParser.add_mutually_exclusive_group"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_mutually_exclusive_group()</span></code></a> 方法也接受一个 <em>required</em> 参数，表示在互斥组中至少有一个参数是需要的:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;PROG&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">group</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">add_mutually_exclusive_group</span><span class="p">(</span><span class="n">required</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">group</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;store_true&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">group</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--bar&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;store_false&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([])</span>
<span class="go">usage: PROG [-h] (--foo | --bar)</span>
<span class="go">PROG: error: one of the arguments --foo --bar is required</span>
</pre></div>
</div>
<p>注意，目前互斥参数组不支持 <a class="reference internal" href="#argparse.ArgumentParser.add_argument_group" title="argparse.ArgumentParser.add_argument_group"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_argument_group()</span></code></a> 的 <em>title</em> 和 <em>description</em> 参数。</p>
</dd></dl>

</div>
<div class="section" id="parser-defaults">
<h3>解析器默认值<a class="headerlink" href="#parser-defaults" title="永久链接至标题">¶</a></h3>
<dl class="method">
<dt id="argparse.ArgumentParser.set_defaults">
<code class="sig-prename descclassname">ArgumentParser.</code><code class="sig-name descname">set_defaults</code><span class="sig-paren">(</span><em class="sig-param">**kwargs</em><span class="sig-paren">)</span><a class="headerlink" href="#argparse.ArgumentParser.set_defaults" title="永久链接至目标">¶</a></dt>
<dd><p>在大多数时候，<a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code></a> 所返回对象的属性将完全通过检查命令行参数和参数动作来确定。 <a class="reference internal" href="#argparse.ArgumentParser.set_defaults" title="argparse.ArgumentParser.set_defaults"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set_defaults()</span></code></a> 则允许加入一些无须任何命令行检查的额外属性:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;foo&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">set_defaults</span><span class="p">(</span><span class="n">bar</span><span class="o">=</span><span class="mi">42</span><span class="p">,</span> <span class="n">baz</span><span class="o">=</span><span class="s1">&#39;badger&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;736&#39;</span><span class="p">])</span>
<span class="go">Namespace(bar=42, baz=&#39;badger&#39;, foo=736)</span>
</pre></div>
</div>
<p>请注意解析器层级的默认值总是会覆盖参数层级的默认值:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="s1">&#39;bar&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">set_defaults</span><span class="p">(</span><span class="n">foo</span><span class="o">=</span><span class="s1">&#39;spam&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([])</span>
<span class="go">Namespace(foo=&#39;spam&#39;)</span>
</pre></div>
</div>
<p>解析器层级默认值在需要多解析器时会特别有用。 请参阅 <a class="reference internal" href="#argparse.ArgumentParser.add_subparsers" title="argparse.ArgumentParser.add_subparsers"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_subparsers()</span></code></a> 方法了解此类型的一个示例。</p>
</dd></dl>

<dl class="method">
<dt id="argparse.ArgumentParser.get_default">
<code class="sig-prename descclassname">ArgumentParser.</code><code class="sig-name descname">get_default</code><span class="sig-paren">(</span><em class="sig-param">dest</em><span class="sig-paren">)</span><a class="headerlink" href="#argparse.ArgumentParser.get_default" title="永久链接至目标">¶</a></dt>
<dd><p>获取一个命名空间属性的默认值，该值是由 <a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_argument()</span></code></a> 或 <a class="reference internal" href="#argparse.ArgumentParser.set_defaults" title="argparse.ArgumentParser.set_defaults"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set_defaults()</span></code></a> 设置的:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="s1">&#39;badger&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">get_default</span><span class="p">(</span><span class="s1">&#39;foo&#39;</span><span class="p">)</span>
<span class="go">&#39;badger&#39;</span>
</pre></div>
</div>
</dd></dl>

</div>
<div class="section" id="printing-help">
<h3>打印帮助<a class="headerlink" href="#printing-help" title="永久链接至标题">¶</a></h3>
<p>在大多数典型应用中，<a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code></a> 将负责任何用法和错误消息的格式化和打印。 但是，也可使用某些其他格式化方法:</p>
<dl class="method">
<dt id="argparse.ArgumentParser.print_usage">
<code class="sig-prename descclassname">ArgumentParser.</code><code class="sig-name descname">print_usage</code><span class="sig-paren">(</span><em class="sig-param">file=None</em><span class="sig-paren">)</span><a class="headerlink" href="#argparse.ArgumentParser.print_usage" title="永久链接至目标">¶</a></dt>
<dd><p>打印一段简短描述，说明应当如何在命令行中发起调用 <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a>。 如果 <em>file</em> 为 <code class="docutils literal notranslate"><span class="pre">None</span></code>，则默认使用 <a class="reference internal" href="sys.html#sys.stdout" title="sys.stdout"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.stdout</span></code></a>。</p>
</dd></dl>

<dl class="method">
<dt id="argparse.ArgumentParser.print_help">
<code class="sig-prename descclassname">ArgumentParser.</code><code class="sig-name descname">print_help</code><span class="sig-paren">(</span><em class="sig-param">file=None</em><span class="sig-paren">)</span><a class="headerlink" href="#argparse.ArgumentParser.print_help" title="永久链接至目标">¶</a></dt>
<dd><p>打印一条帮助消息，包括程序用法和通过 <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> 注册的相关参数信息。 如果 <em>file</em> 为 <code class="docutils literal notranslate"><span class="pre">None</span></code>，则默认使用 <a class="reference internal" href="sys.html#sys.stdout" title="sys.stdout"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.stdout</span></code></a>。</p>
</dd></dl>

<p>还存在这些方法的几个变化形式，它们只返回字符串而不打印消息:</p>
<dl class="method">
<dt id="argparse.ArgumentParser.format_usage">
<code class="sig-prename descclassname">ArgumentParser.</code><code class="sig-name descname">format_usage</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#argparse.ArgumentParser.format_usage" title="永久链接至目标">¶</a></dt>
<dd><p>返回一个包含简短描述的字符串，说明应当如何在命令行中发起调用 <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a>。</p>
</dd></dl>

<dl class="method">
<dt id="argparse.ArgumentParser.format_help">
<code class="sig-prename descclassname">ArgumentParser.</code><code class="sig-name descname">format_help</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#argparse.ArgumentParser.format_help" title="永久链接至目标">¶</a></dt>
<dd><p>反回一个包含帮助消息的字符串，包括程序用法和通过 <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> 注册的相关参数信息。</p>
</dd></dl>

</div>
<div class="section" id="partial-parsing">
<h3>部分解析<a class="headerlink" href="#partial-parsing" title="永久链接至标题">¶</a></h3>
<dl class="method">
<dt id="argparse.ArgumentParser.parse_known_args">
<code class="sig-prename descclassname">ArgumentParser.</code><code class="sig-name descname">parse_known_args</code><span class="sig-paren">(</span><em class="sig-param">args=None</em>, <em class="sig-param">namespace=None</em><span class="sig-paren">)</span><a class="headerlink" href="#argparse.ArgumentParser.parse_known_args" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>有时一个脚本可能只解析部分命令行参数，而将其余的参数继续传递给另一个脚本或程序。 在这种情况下，<a class="reference internal" href="#argparse.ArgumentParser.parse_known_args" title="argparse.ArgumentParser.parse_known_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_known_args()</span></code></a> 方法会很有用处。 它的作用方式很类似 <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code></a> 但区别在于当存在额外参数时它不会产生错误。 而是会返回一个由两个条目构成的元组，其中包含带成员的命名空间和剩余参数字符串的列表。</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;store_true&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;bar&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_known_args</span><span class="p">([</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="s1">&#39;--badger&#39;</span><span class="p">,</span> <span class="s1">&#39;BAR&#39;</span><span class="p">,</span> <span class="s1">&#39;spam&#39;</span><span class="p">])</span>
<span class="go">(Namespace(bar=&#39;BAR&#39;, foo=True), [&#39;--badger&#39;, &#39;spam&#39;])</span>
</pre></div>
</div>
<div class="admonition warning">
<p class="admonition-title">警告</p>
<p><a class="reference internal" href="#prefix-matching"><span class="std std-ref">前缀匹配</span></a> 规则应用于 <code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_known_args()</span></code>。 一个选项即使只是已知选项的前缀部分解析器也能识别该选项，不会将其放入剩余参数列表。</p>
</div>
</div>
<div class="section" id="customizing-file-parsing">
<h3>自定义文件解析<a class="headerlink" href="#customizing-file-parsing" title="永久链接至标题">¶</a></h3>
<dl class="method">
<dt id="argparse.ArgumentParser.convert_arg_line_to_args">
<code class="sig-prename descclassname">ArgumentParser.</code><code class="sig-name descname">convert_arg_line_to_args</code><span class="sig-paren">(</span><em class="sig-param">arg_line</em><span class="sig-paren">)</span><a class="headerlink" href="#argparse.ArgumentParser.convert_arg_line_to_args" title="永久链接至目标">¶</a></dt>
<dd><p>从文件读取的参数（见 <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> 的 <em>fromfile_prefix_chars</em> 关键字参数）将是一行读取一个参数。 <a class="reference internal" href="#argparse.ArgumentParser.convert_arg_line_to_args" title="argparse.ArgumentParser.convert_arg_line_to_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">convert_arg_line_to_args()</span></code></a> 可被重载以使用更复杂的读取方式。</p>
<p>此方法接受从参数文件读取的字符串形式的单个参数 <em>arg_line</em>。 它返回从该字符串解析出的参数列表。 此方法将在每次按顺序从参数文件读取一行时被调用一次。</p>
<p>此方法的一个有用的重载是将每个以空格分隔的单词视为一个参数。 下面的例子演示了如何实现此重载:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">MyArgumentParser</span><span class="p">(</span><span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">convert_arg_line_to_args</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">arg_line</span><span class="p">):</span>
        <span class="k">return</span> <span class="n">arg_line</span><span class="o">.</span><span class="n">split</span><span class="p">()</span>
</pre></div>
</div>
</dd></dl>

</div>
<div class="section" id="exiting-methods">
<h3>退出方法<a class="headerlink" href="#exiting-methods" title="永久链接至标题">¶</a></h3>
<dl class="method">
<dt id="argparse.ArgumentParser.exit">
<code class="sig-prename descclassname">ArgumentParser.</code><code class="sig-name descname">exit</code><span class="sig-paren">(</span><em class="sig-param">status=0</em>, <em class="sig-param">message=None</em><span class="sig-paren">)</span><a class="headerlink" href="#argparse.ArgumentParser.exit" title="永久链接至目标">¶</a></dt>
<dd><p>This method terminates the program, exiting with the specified <em>status</em>
and, if given, it prints a <em>message</em> before that.</p>
</dd></dl>

<dl class="method">
<dt id="argparse.ArgumentParser.error">
<code class="sig-prename descclassname">ArgumentParser.</code><code class="sig-name descname">error</code><span class="sig-paren">(</span><em class="sig-param">message</em><span class="sig-paren">)</span><a class="headerlink" href="#argparse.ArgumentParser.error" title="永久链接至目标">¶</a></dt>
<dd><p>此方法将向标准错误打印包括 <em>message</em> 的用法消息并附带状态码 2 终结程序。</p>
</dd></dl>

</div>
<div class="section" id="intermixed-parsing">
<h3>混合解析<a class="headerlink" href="#intermixed-parsing" title="永久链接至标题">¶</a></h3>
<dl class="method">
<dt id="argparse.ArgumentParser.parse_intermixed_args">
<code class="sig-prename descclassname">ArgumentParser.</code><code class="sig-name descname">parse_intermixed_args</code><span class="sig-paren">(</span><em class="sig-param">args=None</em>, <em class="sig-param">namespace=None</em><span class="sig-paren">)</span><a class="headerlink" href="#argparse.ArgumentParser.parse_intermixed_args" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<dl class="method">
<dt id="argparse.ArgumentParser.parse_known_intermixed_args">
<code class="sig-prename descclassname">ArgumentParser.</code><code class="sig-name descname">parse_known_intermixed_args</code><span class="sig-paren">(</span><em class="sig-param">args=None</em>, <em class="sig-param">namespace=None</em><span class="sig-paren">)</span><a class="headerlink" href="#argparse.ArgumentParser.parse_known_intermixed_args" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>许多 Unix 命令允许用户混用可选参数与位置参数。 <a class="reference internal" href="#argparse.ArgumentParser.parse_intermixed_args" title="argparse.ArgumentParser.parse_intermixed_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_intermixed_args()</span></code></a> 和 <a class="reference internal" href="#argparse.ArgumentParser.parse_known_intermixed_args" title="argparse.ArgumentParser.parse_known_intermixed_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_known_intermixed_args()</span></code></a> 方法均支持这种解析风格。</p>
<p>这些解析器并不支持所有的 argparse 特性，并且当未支持的特性被使用时将会引发异常。 特别地，子解析器，<code class="docutils literal notranslate"><span class="pre">argparse.REMAINDER</span></code> 以及同时包括可选与位置参数的互斥分组是不受支持的。</p>
<p>下面的例子显示了 <a class="reference internal" href="#argparse.ArgumentParser.parse_known_args" title="argparse.ArgumentParser.parse_known_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_known_args()</span></code></a> 与 <a class="reference internal" href="#argparse.ArgumentParser.parse_intermixed_args" title="argparse.ArgumentParser.parse_intermixed_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_intermixed_args()</span></code></a> 之间的差异：前者会将 <code class="docutils literal notranslate"><span class="pre">['2',</span> <span class="pre">'3']</span></code> 返回为未解析的参数，而后者会将所有位置参数收集至 <code class="docutils literal notranslate"><span class="pre">rest</span></code> 中。</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;cmd&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;rest&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="s1">&#39;*&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_known_args</span><span class="p">(</span><span class="s1">&#39;doit 1 --foo bar 2 3&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="go">(Namespace(cmd=&#39;doit&#39;, foo=&#39;bar&#39;, rest=[1]), [&#39;2&#39;, &#39;3&#39;])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_intermixed_args</span><span class="p">(</span><span class="s1">&#39;doit 1 --foo bar 2 3&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="go">Namespace(cmd=&#39;doit&#39;, foo=&#39;bar&#39;, rest=[1, 2, 3])</span>
</pre></div>
</div>
<p><a class="reference internal" href="#argparse.ArgumentParser.parse_known_intermixed_args" title="argparse.ArgumentParser.parse_known_intermixed_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_known_intermixed_args()</span></code></a> 返回由两个条目组成的元组，其中包含带成员的命名空间以及剩余参数字符串列表。 当存在任何剩余的未解析参数字符串时 <a class="reference internal" href="#argparse.ArgumentParser.parse_intermixed_args" title="argparse.ArgumentParser.parse_intermixed_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_intermixed_args()</span></code></a> 将引发一个错误。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.7 新版功能.</span></p>
</div>
</div>
</div>
<div class="section" id="upgrading-optparse-code">
<span id="id2"></span><h2>升级 optparse 代码<a class="headerlink" href="#upgrading-optparse-code" title="永久链接至标题">¶</a></h2>
<p>起初，<a class="reference internal" href="#module-argparse" title="argparse: Command-line option and argument parsing library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">argparse</span></code></a> 曾经尝试通过 <a class="reference internal" href="optparse.html#module-optparse" title="optparse: Command-line option parsing library. (已移除)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> 来维持兼容性。 但是，<a class="reference internal" href="optparse.html#module-optparse" title="optparse: Command-line option parsing library. (已移除)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> 很难透明地扩展，特别是那些为支持新的 <code class="docutils literal notranslate"><span class="pre">nargs=</span></code> 描述方式和更好的用法消息所需的修改。当When most everything in <a class="reference internal" href="optparse.html#module-optparse" title="optparse: Command-line option parsing library. (已移除)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> 中几乎所有内容都已被复制粘贴或打上补丁时，维持向下兼容看来已是不切实际的。</p>
<p><a class="reference internal" href="#module-argparse" title="argparse: Command-line option and argument parsing library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">argparse</span></code></a> 模块在许多方面对标准库的 <a class="reference internal" href="optparse.html#module-optparse" title="optparse: Command-line option parsing library. (已移除)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> 模块进行了增强，包括:</p>
<ul class="simple">
<li><p>处理位置参数。</p></li>
<li><p>支持子命令。</p></li>
<li><p>允许替代选项前缀例如 <code class="docutils literal notranslate"><span class="pre">+</span></code> 和 <code class="docutils literal notranslate"><span class="pre">/</span></code>。</p></li>
<li><p>处理零个或多个以及一个或多个风格的参数。</p></li>
<li><p>生成更具信息量的用法消息。</p></li>
<li><p>提供用于定制 <code class="docutils literal notranslate"><span class="pre">type</span></code> 和 <code class="docutils literal notranslate"><span class="pre">action</span></code> 的更为简单的接口。</p></li>
</ul>
<p>从 <a class="reference internal" href="optparse.html#module-optparse" title="optparse: Command-line option parsing library. (已移除)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> 到 <a class="reference internal" href="#module-argparse" title="argparse: Command-line option and argument parsing library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">argparse</span></code></a> 的部分升级路径:</p>
<ul class="simple">
<li><p>将所有 <a class="reference internal" href="optparse.html#optparse.OptionParser.add_option" title="optparse.OptionParser.add_option"><code class="xref py py-meth docutils literal notranslate"><span class="pre">optparse.OptionParser.add_option()</span></code></a> 调用替换为 <a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code class="xref py py-meth docutils literal notranslate"><span class="pre">ArgumentParser.add_argument()</span></code></a> 调用。</p></li>
<li><p>将 <code class="docutils literal notranslate"><span class="pre">(options,</span> <span class="pre">args)</span> <span class="pre">=</span> <span class="pre">parser.parse_args()</span></code> 替换为 <code class="docutils literal notranslate"><span class="pre">args</span> <span class="pre">=</span> <span class="pre">parser.parse_args()</span></code> 并为位置参数添加额外的 <a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code class="xref py py-meth docutils literal notranslate"><span class="pre">ArgumentParser.add_argument()</span></code></a> 调用。 请注意之前所谓的 <code class="docutils literal notranslate"><span class="pre">options</span></code> 在 <a class="reference internal" href="#module-argparse" title="argparse: Command-line option and argument parsing library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">argparse</span></code></a> 上下文中被称为 <code class="docutils literal notranslate"><span class="pre">args</span></code>。</p></li>
<li><p>通过使用 <a class="reference internal" href="#argparse.ArgumentParser.parse_intermixed_args" title="argparse.ArgumentParser.parse_intermixed_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_intermixed_args()</span></code></a> 而非 <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code></a> 来替换 <a class="reference internal" href="optparse.html#optparse.OptionParser.disable_interspersed_args" title="optparse.OptionParser.disable_interspersed_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">optparse.OptionParser.disable_interspersed_args()</span></code></a>。</p></li>
<li><p>将回调动作和 <code class="docutils literal notranslate"><span class="pre">callback_*</span></code> 关键字参数替换为 <code class="docutils literal notranslate"><span class="pre">type</span></code> 或 <code class="docutils literal notranslate"><span class="pre">action</span></code> 参数。</p></li>
<li><p>将 <code class="docutils literal notranslate"><span class="pre">type</span></code> 关键字参数字符串名称替换为相应的类型对象（例如 int, float, complex 等）。</p></li>
<li><p>将 <code class="xref py py-class docutils literal notranslate"><span class="pre">optparse.Values</span></code> 替换为 <a class="reference internal" href="#argparse.Namespace" title="argparse.Namespace"><code class="xref py py-class docutils literal notranslate"><span class="pre">Namespace</span></code></a> 并将 <code class="xref py py-exc docutils literal notranslate"><span class="pre">optparse.OptionError</span></code> 和 <code class="xref py py-exc docutils literal notranslate"><span class="pre">optparse.OptionValueError</span></code> 替换为 <code class="xref py py-exc docutils literal notranslate"><span class="pre">ArgumentError</span></code>。</p></li>
<li><p>将隐式参数字符串例如使用标准 Python 字典语法的 <code class="docutils literal notranslate"><span class="pre">%default</span></code> 或 <code class="docutils literal notranslate"><span class="pre">%prog</span></code> 替换为格式字符串，即 <code class="docutils literal notranslate"><span class="pre">%(default)s</span></code> 和 <code class="docutils literal notranslate"><span class="pre">%(prog)s</span></code>。</p></li>
<li><p>将 OptionParser 构造器 <code class="docutils literal notranslate"><span class="pre">version</span></code> 参数替换为对 <code class="docutils literal notranslate"><span class="pre">parser.add_argument('--version',</span> <span class="pre">action='version',</span> <span class="pre">version='&lt;the</span> <span class="pre">version&gt;')</span></code> 的调用。</p></li>
</ul>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">目录</a></h3>
  <ul>
<li><a class="reference internal" href="#"><code class="xref py py-mod docutils literal notranslate"><span class="pre">argparse</span></code> --- 命令行选项、参数和子命令解析器</a><ul>
<li><a class="reference internal" href="#example">示例</a><ul>
<li><a class="reference internal" href="#creating-a-parser">创建一个解析器</a></li>
<li><a class="reference internal" href="#adding-arguments">添加参数</a></li>
<li><a class="reference internal" href="#parsing-arguments">解析参数</a></li>
</ul>
</li>
<li><a class="reference internal" href="#argumentparser-objects">ArgumentParser 对象</a><ul>
<li><a class="reference internal" href="#prog">prog</a></li>
<li><a class="reference internal" href="#usage">usage</a></li>
<li><a class="reference internal" href="#description">描述</a></li>
<li><a class="reference internal" href="#epilog">epilog</a></li>
<li><a class="reference internal" href="#parents">parents</a></li>
<li><a class="reference internal" href="#formatter-class">formatter_class</a></li>
<li><a class="reference internal" href="#prefix-chars">prefix_chars</a></li>
<li><a class="reference internal" href="#fromfile-prefix-chars">fromfile_prefix_chars</a></li>
<li><a class="reference internal" href="#argument-default">argument_default</a></li>
<li><a class="reference internal" href="#allow-abbrev">allow_abbrev</a></li>
<li><a class="reference internal" href="#conflict-handler">conflict_handler</a></li>
<li><a class="reference internal" href="#add-help">add_help</a></li>
</ul>
</li>
<li><a class="reference internal" href="#the-add-argument-method">add_argument() 方法</a><ul>
<li><a class="reference internal" href="#name-or-flags">name or flags</a></li>
<li><a class="reference internal" href="#action">action</a></li>
<li><a class="reference internal" href="#nargs">nargs</a></li>
<li><a class="reference internal" href="#const">const</a></li>
<li><a class="reference internal" href="#default">默认值</a></li>
<li><a class="reference internal" href="#type">type -- 类型</a></li>
<li><a class="reference internal" href="#choices">choices</a></li>
<li><a class="reference internal" href="#required">required</a></li>
<li><a class="reference internal" href="#help">help</a></li>
<li><a class="reference internal" href="#metavar">metavar</a></li>
<li><a class="reference internal" href="#dest">dest</a></li>
<li><a class="reference internal" href="#action-classes">Action 类</a></li>
</ul>
</li>
<li><a class="reference internal" href="#the-parse-args-method">parse_args() 方法</a><ul>
<li><a class="reference internal" href="#option-value-syntax">选项值语法</a></li>
<li><a class="reference internal" href="#invalid-arguments">无效的参数</a></li>
<li><a class="reference internal" href="#arguments-containing">包含 <code class="docutils literal notranslate"><span class="pre">-</span></code> 的参数</a></li>
<li><a class="reference internal" href="#argument-abbreviations-prefix-matching">参数缩写（前缀匹配）</a></li>
<li><a class="reference internal" href="#beyond-sys-argv">在 <code class="docutils literal notranslate"><span class="pre">sys.argv</span></code> 以外</a></li>
<li><a class="reference internal" href="#the-namespace-object">命名空间对象</a></li>
</ul>
</li>
<li><a class="reference internal" href="#other-utilities">其它实用工具</a><ul>
<li><a class="reference internal" href="#sub-commands">子命令</a></li>
<li><a class="reference internal" href="#filetype-objects">FileType 对象</a></li>
<li><a class="reference internal" href="#argument-groups">参数组</a></li>
<li><a class="reference internal" href="#mutual-exclusion">互斥</a></li>
<li><a class="reference internal" href="#parser-defaults">解析器默认值</a></li>
<li><a class="reference internal" href="#printing-help">打印帮助</a></li>
<li><a class="reference internal" href="#partial-parsing">部分解析</a></li>
<li><a class="reference internal" href="#customizing-file-parsing">自定义文件解析</a></li>
<li><a class="reference internal" href="#exiting-methods">退出方法</a></li>
<li><a class="reference internal" href="#intermixed-parsing">混合解析</a></li>
</ul>
</li>
<li><a class="reference internal" href="#upgrading-optparse-code">升级 optparse 代码</a></li>
</ul>
</li>
</ul>

  <h4>上一个主题</h4>
  <p class="topless"><a href="time.html"
                        title="上一章"><code class="xref py py-mod docutils literal notranslate"><span class="pre">time</span></code> --- 时间的访问和转换</a></p>
  <h4>下一个主题</h4>
  <p class="topless"><a href="getopt.html"
                        title="下一章"><code class="xref py py-mod docutils literal notranslate"><span class="pre">getopt</span></code> --- C 风格的命令行选项解析器</a></p>
  <div role="note" aria-label="source link">
    <h3>本页</h3>
    <ul class="this-page-menu">
      <li><a href="../bugs.html">提交 Bug</a></li>
      <li>
        <a href="https://github.com/python/cpython/blob/3.7/Doc/library/argparse.rst"
            rel="nofollow">显示源代码
        </a>
      </li>
    </ul>
  </div>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>导航</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="总目录"
             >索引</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python 模块索引"
             >模块</a> |</li>
        <li class="right" >
          <a href="getopt.html" title="getopt --- C 风格的命令行选项解析器"
             >下一页</a> |</li>
        <li class="right" >
          <a href="time.html" title="time --- 时间的访问和转换"
             >上一页</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">3.7.8 Documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python 标准库</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="allos.html" >通用操作系统服务</a> &#187;</li>
    <li class="right">
        

    <div class="inline-search" style="display: none" role="search">
        <form class="inline-search" action="../search.html" method="get">
          <input placeholder="快速搜索" type="text" name="q" />
          <input type="submit" value="转向" />
          <input type="hidden" name="check_keywords" value="yes" />
          <input type="hidden" name="area" value="default" />
        </form>
    </div>
    <script type="text/javascript">$('.inline-search').show(0);</script>
         |
    </li>

      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">版权所有</a> 2001-2020, Python Software Foundation.
    <br />
    Python 软件基金会是一个非盈利组织。
    <a href="https://www.python.org/psf/donations/">请捐助。</a>
    <br />
    最后更新于 6月 29, 2020.
    <a href="../bugs.html">发现了问题</a>？
    <br />
    使用<a href="http://sphinx.pocoo.org/">Sphinx</a>2.3.1 创建。
    </div>

  </body>
</html>